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

标签 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()

非常关键的一点,这是我在我的 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,这显然是第一个引用的函数。所有其他都会导致编译错误(见下文)。

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

无法从程序集“test1DLL_highest,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null”加载类型“test1DLL_highest.Form1”,因为方法“multiplyints”没有实现(无 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();

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

关于c# - 在 C# 应用程序中只能使用 C++ DLL 中的 1/4 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413800/

相关文章:

c# - .NET 4 是否支持任何 6-Sigma 计算?

c++ - 使用 Qt 播放 *.avi 文件

c++ - 尝试使用 tensorflow 的 C++ API 时出错

java - UnsatisfiedLinkError + JNLP + Applet + DLL

c# - 将 DLL 合并到程序集或嵌入到资源中 - 哪个更好?

delphi - 如何在delphi中从Fortran DLL调用函数?

c# - 如果未进行任何更改, Entity Framework DbContext 是否会保存更改?

c# - 得到两个椭圆而不是一个

c# - wcf 基于任务的异步模式

c++ - 内联代码应该有多小