I have a project, where I must connect to a library that is C based, and I was not able to get at the functions from C# using the DLLImport. I have to use a project that is C++/CLI based to surface these functions for use. (more to that story but not important).
I studied C++ over 10 years ago, so forgive me if this seems like it is naive.
I purchased a few books on the C++/CLI implementation last year, and have some grasp of what is involved — I only dug into those books for this project. (I have been a programmer for a long time).
I thought I had better start a small project example project to familiarize myself with what will be involved, to make sure I could compile, etc. I started a project using Visual Studio 2008 SP1; Visual C++ > CLR > Class Library. In the project — I want to use both managed and native from the DLL. So the /clr switch is used.
I have used other names in the real code; but this is very, very close. (there are no other files, or functions at this point)
Header:
//myWrapper.h
#pragma once
using namespace System;
namespace myWrapper {
public ref class myWrappedService {
myWrappedService();
bool Connected(String ^user,String ^password,String ^domain);
}
};
And the implementation has this.
//myWrapper.cpp
//This is the main DLL file
#include "stdafx.h"
#include "myWrapper.h"
using namespace System;
public ref class myWrappedService
{
public:
myWrappedService() {}
bool Connected(String ^user,String ^password,String ^domain)
{
//just a simple result to start - no real functionality
bool result = false;
return result;
}
};
That is the code — that compiles but gets linker errors.
error LNK2020: unresolved token (06000002)
myWrapper.myWrappedService::Connectedfatal error LNK1120: 1 unresolved external.
This looked dead easy — and I might be thinking to much from a C# approach. I expect this to be something simple — but I am not familiar with what I should be seeing in the CLI approach. (I spent a few hours looking for answers and finally feel I need to post a question where it might get answered).
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Linker Tools Error LNK2020 |
Linker Tools Error LNK2020 |
11/04/2016 |
LNK2020 |
LNK2020 |
4dd017d0-5e83-471b-ac8a-538ac1ed6870 |
unresolved token ‘token’
Similar to an undefined external error, except that the reference is via metadata. In metadata, all functions and data must be defined.
To resolve:
-
Define the missing function or data, or
-
Include the object file or library in which the missing function or data is already defined.
Examples
The following sample generates LNK2020.
// LNK2020.cpp // compile with: /clr /LD ref struct A { A(int x); // LNK2020 static int f(); // LNK2020 }; // OK ref struct B { B(int x) {} static int f() { return 0; } };
LNK2020 will also occur if you create a variable of a managed template type, but do not also instantiate the type.
The following sample generates LNK2020.
// LNK2020_b.cpp // compile with: /clr template <typename T> ref struct Base { virtual void f1() {}; }; template <typename T> ref struct Base2 { virtual void f1() {}; }; int main() { Base<int>^ p; // LNK2020 Base2<int>^ p2 = gcnew Base2<int>(); // OK };
Я создаю новый абстрактный класс в C ++ / CLI и столкнулся со странной ошибкой. Есть много вопросов, похожих на этот, но ни один из ответов не может мне помочь.
В этом новом классе я получаю следующую ошибку:
error LNK2020: unresolved token (06000002) Foo::execute
Это h-файл:
#pragma once
using namespace System::IO::Ports;
using namespace System;
public ref class Foo
{
protected:
SerialPort^ port;
public:
Foo(SerialPort^ sp);
virtual array<Byte>^ execute();
};
Это cpp-файл:
#include "StdAfx.h"#include "Foo.h"
Foo::Foo(SerialPort^ sp)
{
this->port = sp;
}
Обратите внимание, что когда я закомментирую virtual array<Byte>^ execute();
линия, все компилируется отлично. Кроме того, когда я удаляю virtual
модификатор и добавить реализацию execute()
в cpp-файле это тоже работает.
4
Решение
Вы уже дали ответ сами:
Кроме того, когда я удаляю виртуальный модификатор и добавляю реализацию execute () в cpp-файл, он также работает.
Вы объявили метод execute
в шапке, но его реализация отсутствует. Это именно то, что говорит вам ошибка компоновщика.
В этом случае декларация как virtual
не имеет значения.
Если вы хотите создать абстрактный класс, вы можете найти более подробную информацию в многочисленных статьях онлайн (например, Викиучебники: Абстрактные Занятия)
6
Другие решения
Вы должны либо реализовать метод, либо удалить объявление из заголовка. (виртуальное ключевое слово в данном случае не имеет значения)
Пожалуйста, задайте вопрос, если есть.
3
Добрый день, Господа!
Пишу приложение Windows Forms Application. Возникла проблема при работе с шрифтами и OpenGL.
При вызове функции ChooseFontA(&cf) появляется ошибка LNK2020.
Прошу помощи!
C++ | ||
|
Добавлено через 21 минуту
Вообще любая работа, касающаяся font, вызывает эту ошибку!
Уже много способов перепробовал, и из MSDN, и из книг. Результат все-равно один и тот же.
Configuration:
VS 2017
ISO C++17
Multi-Threaded DLL project.
I’ve encountered a strange error, I haven’t been able to figure out. Other than being a Singleton, this is a pretty basic class.
This is one file contained within a .DLL project, which is compiled with /CLR enabled, although this particular class is not a managed class.
(.h)
#pragma once
#include <string>
#include <memory>
using namespace std;
public class SessionInfo
{
public:
static std::string UserId;
static std::string UserName;
static std::string UserLoginDateTime;
private:
static SessionInfo& Instance()
{
static std::unique_ptr<SessionInfo> _instance(new SessionInfo());
return *_instance;
}
private:
SessionInfo();
SessionInfo(const SessionInfo &old); // disable copy constructor
const SessionInfo &operator=(const SessionInfo &old); //disable assignment operator
};
.cpp
#include «SessionInfo.h»
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
SessionInfo::SessionInfo()
{
}
void SessionInfo::setCurrentDateTime()
{
struct tm newtime;
__time32_t aclock;
char buffer[32];
errno_t errNum;
_time32(&aclock); // Get time in seconds.
_localtime32_s(&newtime, &aclock); // Convert time to struct tm form.
errNum = asctime_s(buffer, 32, &newtime);
if (!errNum)
{
//UserLoginDateTime.clear();
//UserLoginDateTime.append(buffer);
}
}
If built, as is, it compiles and links without error. However, if I uncomment ‘UserLoginDateTime.clear()’ and/or ‘UserLoginDateTime.append(buffer)’ I receive the following linker errors:
SessionInfo.obj : error LNK2020: unresolved token (0A000531) «public: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > SessionInfo::UserLoginDateTime» (?UserLoginDateTime@SessionInfo@@2V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)
SessionInfo.obj : error LNK2001: unresolved external symbol «public: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > SessionInfo::UserLoginDateTime» (?UserLoginDateTime@SessionInfo@@2V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)
I thought that I might be missing a .lib dependency, although if that is the case, I don’t know which one I’m missing.
Assistance would be appreciated.
Thanks