在C#应用程序中只能使用C++ DLL的1/4函数

mgi*_*son 1 c# c++ dll pinvoke dllimport

转换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()
Run Code Online (Sandbox Code Playgroud)

非常关键的一点,就是我在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();
Run Code Online (Sandbox Code Playgroud)

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

如果我没有注释掉上面的代码并转到外部引用所有这些功能.我在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).

我会想象排序可以排序一切.

干杯.

Ree*_*sey 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();
Run Code Online (Sandbox Code Playgroud)

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

  • 还要确保您的外壳与DLL函数名称匹配.除了`subtractInts`之外,你对它们有所不同 (3认同)