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

Can only use 1/4 functions from C++ DLL in C# application

本文关键字:中的 DLL 函数 c++ 应用程序      更新时间:2023-10-16

在c#中转换c++ DLL时遇到了点麻烦。

它正在工作…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#调用时唯一有效的函数是subtractInts,这显然是首先引用的函数。所有其他的都会在编译时导致错误(见下文)。

如果我没有注释掉上面的代码并从外部引用所有这些函数。我在multipyint (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).

我认为排序可以对所有东西进行排序。

欢呼。

您需要将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发现方法发现)。