gpt4 book ai didi

visual-c++ - Visual C++/CLI - CLR 类 - LNK2020 错误 - 如何修复?

转载 作者:行者123 更新时间:2023-12-01 23:25:59 25 4
gpt4 key购买 nike

我有一个项目,我必须在其中连接到一个基于 C 的库,但我无法使用 DLLImport 从 C# 获取函数。我必须使用基于 C++/CLI 的项目来显示这些函数以供使用。 (更多关于那个故事但不重要)。

我在 10 多年前学习了 C++,所以如果这看起来很幼稚,请原谅我。
去年我买了几本关于 C++/CLI 实现的书,对其中的内容有了一些了解——我只是为了这个项目才翻阅那些书。 (我当了很长时间的程序员)。

我想我最好开始一个小项目示例项目,以熟悉将涉及的内容,确保我可以编译等。我使用 Visual Studio 2008 SP1 开始了一个项目; Visual C++ > CLR > 类库。在项目中 - 我想使用 DLL 中的托管和 native 。所以使用/clr 开关。

我在实际代码中使用了其他名称;但这非常非常接近。 (此时没有其他文件或函数)

标题:

//myWrapper.h
#pragma once
using namespace System;
namespace myWrapper {
public ref class myWrappedService {
myWrappedService();
bool Connected(String ^user,String ^password,String ^domain);
}
};

实现有这个。

//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;
}
};

这就是代码 - 编译但出现链接器错误。

error LNK2020: unresolved token (06000002) myWrapper.myWrappedService::Connected

fatal error LNK1120: 1 unresolved external.

这看起来非常简单 - 我可能会从 C# 方法中考虑很多。我希望这会很简单 - 但我不熟悉我应该在 CLI 方法中看到的内容。 (我花了几个小时寻找答案,最后觉得我需要发布一个可能会得到回答的问题)。

最佳答案

namespace myWrapper {

从那里就出错了。您的 .h 文件在该命名空间内声明了一个类,其名称为 myWrapper::myWrappedService。您的 .cpp 文件声明了 另一个 不在命名空间中的类,它的名称是::myWrappedService。不同的名字,编译器不会提示看到同一个类定义了两次。第一个类没有 Connected 方法的实现,这就是链接器提示的原因。

sad_man 的片段也有同样的缺陷。第一个片段定义了::myWrappedService::Connected() 方法。命名空间错误。第二个片段与你的有同样的缺陷。

当您在托管代码中编写类库时,您不需要 .h 文件。程序集中的元数据起着同样的作用,它包含程序集中类型的声明。您的项目中没有其他 .cpp 文件需要类的声明,不需要 .h。所以只需将所有内容写入 .cpp 文件即可:

#include "stdafx.h"
// Note: header file removed

using namespace System;

namespace myWrapper {

public ref class myWrappedService
{
public:
myWrappedService() {}
void Connect(String ^user, String ^password, String ^domain)
{
throw gcnew NotImplementedException;
}
};
}

关于visual-c++ - Visual C++/CLI - CLR 类 - LNK2020 错误 - 如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com