如何将别人用c++写的linkdll/lib在C#中调用API?

How to link dll/lib written in c++ by others and call the API in C#?

我想在我的C#应用程序中调用别人写的API

API 通过 .dll、.lib 和 .h 文件提供并用 C++ 编写。请注意,我没有dll或lib的源代码或实现。

问题一: 如何link将c++写的dll,lib,.h文件转成C#项目?

问题二: 如何在完成 linking dll 和 lib 后在 C# 中调用 C++ API?

问题三: c++ API 中的某些函数采用指针参数。如何在 C# 中传递指针参数?

下面是我想在 C# 应用程序中调用的 C++ 函数原型:

unsigned long function1 ( unsigned long arg1,
unsigned long addr,
unsigned long *NumberOfBytes,
unsigned long *Data) 

你想要的是 Platform InvokeP/Invoke。 P/Invoke 是一种允许您从托管代码访问非托管库中的结构、回调和函数的技术。大多数 P/Invoke API 包含在两个名称空间中:SystemSystem.Runtime.InteropServices。使用这两个命名空间将允许您访问描述您希望如何与本机组件通信的属性。

您不必在 C++ 上进行任何链接,C# 项目就可以调用它。只需确保将要访问的方法设置为 __declspec(dllexport)。请记住,您不能从静态库中调用 Pinvoke,您必须将其设为动态库 dll。在 Linux 系统上 .so(共享对象)文件。指针参数由 refout

传递

这里有两篇关于该主题的重要文章:

MSDN Article:1
MSDN Article:2
DLL Exporting Article

  1. 你不能 link C/C++ dll 到 C#。

  2. 你只能通过P/Invoke

  3. 调用C/C++

For example, you have cpp.dll which is exporting int cplusplus_testmethod();
you can call this method by applying DllImportAttribute

[DllImport("cpp")] // "cpp" or "cpp.dll"
public static extern int cplusplus_testmethod();

// Calling cpp.dll!cplusplus_testmethod
cplusplus_testmethod();

For more information, read MSDN document about P/Invoke.
Platform Invoke Example (MSDN)
Platform Invoke Tutorials (MSDN)

  1. 您可以使用 refoutIntPtr。 (您也可以使用 Array

ref 用于 R/Wout 用于只写。例如,

int cplusplus_testmethod(int* age) {
    *age = 10;
}

此代码采用 int* 作为参数并将其值设置为 10。(方法不读取其值,仅写入)因此在这种情况下,您可以使用 out.


int cplusplus_testmethod(int* age) {
    if (*age < 0) *age = 0;
    *age = 40;
}

此代码也采用 int* 作为参数,但它读取 age 的值,并将其值设置为 40。因此您可以使用 ref。 (您不能为此使用 out

或者您可以使用 Marshal class 来处理指针。

Marshal (MSDN)