1

将 C++ DLL 转换为在 C# 中使用时遇到了一些麻烦。

它正在工作.. DLL 中的第一个 C++ 函数只是:int subtractInts(int x, int y)并且它的典型主体工作没有问题。所有其他功能都一样简单,并且已经过测试。但是,我一直在关注教程并做一些时髦的事情,以将 C# 中的代码用作 C++ DLL(为了可移植性)。

我的步骤是:

• 创建一个 C++ 类,对其进行测试并保存 - 仅使用“class.cpp”和“class.h”文件 • 在 Visual Studio 2010 中创建一个 Win32 库项目,在启动时选择 DLL,并为我想要的每个函数暴露给 C#.. 下面的代码

extern "C" __declspec(dllexport) int addInts(int x, int y)
extern "C" __declspec(dllexport) int multiplyInts(int x, int y)
extern "C" __declspec(dllexport) int subtractInts(int x, int y)
extern "C" __declspec(dllexport) string returnTestString()

非常关键的一点,这是我在我的 DLL 中将它们外部化的顺序。

然后作为测试,因为我之前确实遇到过这个问题。我在我的 C# 项目中以不同的方式引用了它们

   [DllImport("C:\\cppdll\\test1\\testDLL1_medium.dll", CallingConvention = CallingConvention.Cdecl)]

    public static extern int subtractInts(int x, int y);
    public static extern int multiplyints(int x, int y);
    public static extern int addints(int x, int y);
    public static extern string returnteststring();

从 C# 调用时唯一起作用的函数是减法,这显然是首先引用的函数。所有其他都会在编译时导致错误(见下文)。

如果我不注释掉上面的代码并去外部引用所有这些函数。我在 multipyInts(int x, int y) 处收到以下错误。

Could not load type 'test1DLL_highest.Form1' from assembly 'test1DLL_highest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method 'multiplyints' has no implementation (no RVA).

我会想象排序可以对所有内容进行排序。

干杯。

4

1 回答 1

5

您需要添加DllImportAttribute所有四种方法,删除路径,并修复您的套管:

[DllImport("testDLL1_medium.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int subtractInts(int x, int y);
[DllImport("testDLL1_medium.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int multiplyInts(int x, int y);
[DllImport("testDLL1_medium.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int addInts(int x, int y);
[DllImport("testDLL1_medium.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern string returnTestString();

还要确保本机 DLL 与托管程序集位于同一位置(或可通过常规 DLL 发现方法发现)。

于 2013-03-14T15:45:56.093 回答