例如,对于Linux:
1) 创建一个C
文件,libtest.c
包含以下内容:
#include <stdio.h>
void print(const char *message)
{
printf("%s\\n", message);
}
这是printf的一个简单的伪包装.但表示要调用的库中的任何C
函数.如果你有一个C++
函数,别忘了把exterC
放进go ,以免损坏名字.
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.因此,在"/usr/lib"这样的标准库路径中,您可能会看到一个系统.DllNotFoundException,要修复此问题,可以移动libtest.因此,为了/usr/lib,或者更好,只需将CWD添加到库路径:export LD_LIBRARY_PATH=pwd
here个学分
EDIT
对于Windows来说,没什么不同.
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);
}
}