我有一个 C 库,想从 C# 应用程序调用这个库中的函数。我尝试通过将 C lib 文件添加为链接器输入并将源文件添加为附加依赖项来在 C lib 上创建 C++/CLI 包装器。
是否有更好的方法来实现这一点,因为我不确定如何将 C 输出添加到 C# 应用程序。
我的 C 代码 -
__declspec(dllexport) unsigned long ConnectSession(unsigned long handle,
unsigned char * publicKey,
unsigned char publicKeyLen);
我的 CPP 包装器 -
long MyClass::ConnectSessionWrapper(unsigned long handle,
unsigned char * publicKey,
unsigned char publicKeyLen)
{
return ConnectSession(handle, publicKey, publicKeyLen);
}
最佳答案
对于 Linux,示例将是:
1) 创建一个 C
文件,libtest.c
,内容如下:
#include <stdio.h>
void print(const char *message)
{
printf("%s\\n", message);
}
这是一个简单的 printf 伪包装器。但表示要调用的库中的任何 C
函数。如果您有一个 C++
函数,请不要忘记放置 extern C
以避免混淆名称。
2) 创建C#
文件
using System;
using System.Runtime.InteropServices;
public class Tester
{
[DllImport("libtest.so", EntryPoint="print")]
static extern void print(string message);
public static void Main(string[] args)
{
print("Hello World C# => C++");
}
}
3) 除非你的库 libtest.so 位于“/usr/lib”之类的标准库路径中,否则你很可能会看到 System.DllNotFoundException,要解决此问题,你可以将你的 libtest.so 移动到/usr/lib,或者更好的是,只需将您的 CWD 添加到库路径:export LD_LIBRARY_PATH=pwd
来自 here 的学分
编辑
对于 Windows,差别不大。
以 here 为例, 你只需要在你的 *.cpp
文件中附上你的方法 extern "C"
有点像
extern "C"
{
//Note: must use __declspec(dllexport) to make (export) methods as 'public'
__declspec(dllexport) void DoSomethingInC(unsigned short int ExampleParam, unsigned char AnotherExampleParam)
{
printf("You called method DoSomethingInC(), You passed in %d and %c\n\r", ExampleParam, AnotherExampleParam);
}
}//End 'extern "C"' to prevent name mangling
然后,编译,并在您的 C# 文件中执行
[DllImport("C_DLL_with_Csharp.dll", EntryPoint="DoSomethingInC")]
public static extern void DoSomethingInC(ushort ExampleParam, char AnotherExampleParam);
然后直接使用它:
using System;
using System.Runtime.InteropServices;
public class Tester
{
[DllImport("C_DLL_with_Csharp.dll", EntryPoint="DoSomethingInC")]
public static extern void DoSomethingInC(ushort ExampleParam, char AnotherExampleParam);
public static void Main(string[] args)
{
ushort var1 = 2;
char var2 = '';
DoSomethingInC(var1, var2);
}
}
关于c - 是否可以从 C#.Net 调用 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425202/