我有一个C库,想从C#应用程序调用这个库中的函数.我try 在Clib上创建一个C++/CLI包装器,方法是将Clib文件作为链接器输入添加,并将源文件作为附加依赖项添加.

有没有更好的方法来实现这一点,因为我不确定如何将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++函数,别忘了把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);
            }
    }

C++相关问答推荐

如何从TPS特定的TGPT_PUBLIC数据 struct 中以OpenSSL的EVP_PKEY

有什么方法可以检测SunOS上的SparcWorks吗?

与unions 的未定义行为

如何将不同长度的位转换成字节数组?

无法用C++编译我的单元测试

C:fopen是如何实现二进制模式和文本模式的?

这是一个合法的C Strdup函数吗?

将uintptr_t添加到指针是否对称?

Kdb:仅升级指定的列

为什么数组的最后一个元素丢失了?

S和查尔有什么不同[1]?

我在反转双向链表时遇到问题

如何使这个While循环在新行上结束

C-try 将整数和 struct 数组存储到二进制文件中

是否有单独的缓冲区用于读写库调用?

如何编写postgresql支持函数

atoi函数最大长-长误差的再创造

我可以使用Windows SDK';s IN6_IS_ADDR_LOOPBACK等,尽管没有文档?

一元运算符

创建 makefile 来编译位于不同目录中的多个源文件