【问题标题】:Can only use 1/4 functions from C++ DLL in C# application在 C# 应用程序中只能使用来自 C++ DLL 的 1/4 函数
【发布时间】:2013-03-14 15:44:21
【问题描述】:

在转换用于 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# 调用时唯一起作用的函数是减法函数,这显然是首先引用的函数。所有其他都会在编译时导致错误(见下文)。

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

我认为排序可以对所有内容进行排序。

干杯。

【问题讨论】:

  • 用 DLLI 赋予它们所有属性

标签: c# c++ dll pinvoke dllimport


【解决方案1】:

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

【讨论】:

  • 好的,这已经解决了最初的错误,但是现在当我尝试调用其中一个函数时,例如label2.Text = multiplyInts(4, 6).ToString(); 我得到这个错误.. "Error 1 The name 'multiplyInts' does not exist in the current context \\selafap01\homedrives\mgibson\my documents\visual studio 2010\Projects\test1DLL_highest\test1DLL_highest\Form1.cs 32 27 test1DLL_highest (很明显它被编译的目录,但是 DLL 没有处理所有这些吗?
  • @mgibson 您应该确保非托管 DLL 位于(C# 项目的)可执行文件夹中,而不是指定“完整路径”。
  • 还要确保您的大小写与 DLL 函数名称匹配。除了 subtractInts
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 2010-10-08
  • 1970-01-01
  • 2021-03-15
  • 2012-05-12
  • 1970-01-01
相关资源
最近更新 更多