【问题标题】:How to link dll/lib written in c++ by others and call the API in C#? [duplicate]如何链接别人用c++编写的dll/lib并在C#中调用API? [复制]
【发布时间】:2018-12-07 01:53:46
【问题描述】:

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

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

问题 1: 如何将c++编写的dll、lib和.h文件链接到C#项目?

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

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

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

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

【问题讨论】:

标签: c# c++ pointers dll lib


【解决方案1】:

您想要的称为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

【讨论】:

    【解决方案2】:
    1. 您不能将 C/C++ dll 链接到 C#。

    2. 只能通过P/Invoke调用C/C++

    例如,您有 cpp.dll 正在导出 int cplusplus_testmethod();
    你可以通过应用DllImportAttribute来调用这个方法

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

    有关详细信息,请阅读有关 P/Invoke 的 MSDN 文档。
    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 类来处理指针。

    Marshal (MSDN)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多