gpt4 book ai didi

c# - 在C#中调用c dll

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:55 24 4
gpt4 key购买 nike

问题介绍:

我必须通过DLL 文件、LIB 文件和函数声明为dllimport 的c 头文件提供的API 来控制某个设备。

当我在 C++ 项目中使用 API 时,一切正常 - 我包含了 header 、lib、dll,并调用了 header 文件中声明的函数。

当尝试使用 [DllImport] 属性从 C#.NET 项目调用这些函数时,问题就开始了:函数是用准确的名称和参数声明的,并且运行代码没有抛出任何异常。然而设备根本没有响应,就像这些功能从未真正被调用过一样。

在C头文件中是如何声明的:

int __declspec(dllimport) Init_Card_RTx(unsigned short device_num, unsigned short enabled_channels, unsigned short xmt_channels);

在C#中是如何声明的:

[DllImport(Path, CallingConvention = CallingConvention.Cdecl, EntryPoint = "Init_Card_RTx")]
public static extern int Init_Card_RTx(UInt16 device_num, UInt16 enabled_channels, UInt16 xmt_channels);

问题:

  • 是因为 header 中的函数被声明为 dllimport 吗?
  • 在这种情况下,我是否必须使用声明为 dllexport 的 C++ 函数包装 DLL?
  • 要从 C# 访问 C DLL 需要哪些步骤?
  • 在 C# 项目中,是否还必须包含 LIB 文件?不仅仅是 DLL 文件本身?

最佳答案

Is that because the functions in the headers are declared dllimport?

可能吧。函数需要导出。它们是否导出取决于它们的 DLL 是如何由提供给您的人编译的。我猜它们应该是这样(否则 C++ 代码会尝试导入它们并失败)。
解决此类问题时,我做的第一件事是加载 Dependency Walker 中的 DLL。它将向您显示所有导出的函数。如果它们没有出现,则不会导出,C# 也无法调用它们。如果它们出现了,那么您就没事了,您不需要更改任何 C 代码或创建任何包装函数。

In that case, do I have to wrap the DLL with C++ functions declared as dllexport?

没有。 C# 只能使用 DllImport 调用 C 函数。 C++ 做 name mangling导出函数时,这会使事情变得一团糟,而且通常无法正常工作。

您需要做的是以某种方式导出您的函数。我的猜测是它们已经导出,但如果没有,您可以像这样创建一些包装函数。

int __declspec(dllexport) Init_Card_RTx(unsigned short device_num, unsigned short enabled_channels, unsigned short xmt_channels) {
// just call the other function here
}

这些应该使函数导出,你应该看到它出现在 dependency walker 中。

What are the steps required for a C DLL to be accessible from C#?

CLR 必须能够找到 dll(通常你只需将它放在与 C# exe 相同的目录中),并且函数必须导出为 C 函数。差不多就是这样。

In the C# project, do I have to include the LIB file as well? not just the DLL file itself?

您根本不需要在 C# 项目中包含任何内容,只需包含 public static extern 包装函数及其 DllImport 属性即可。只要 CLR 可以在运行时找到 dll,这就是您所需要的。如果它在运行时找不到它,您应该在调用第一个导入方法时得到一个异常。

PS:获取 Dependency walker。对于这种事情,我极力推荐它

关于c# - 在C#中调用c dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com