该示例将针对Linux:
1)创建一个C文件,libtest.c内容如下:
#include <stdio.h>
void print(const char *message)
{
  printf("%s\\n", message);
}
那是printf的一个简单的伪包装器。但是代表C您要调用的库中的任何函数。如果您有一个C++函数,别忘了加上externC以避免改变名称。
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)除非在标准库路径(如“ / usr / lib”)中具有库libtest.so,否则您很可能会看到System.DllNotFoundException,要解决此问题,可以将libtest.so移至/ usr / lib,或者更好的是,只需将您的CWD添加到库路径中: export LD_LIBRARY_PATH=pwd
从这里学分
编辑
对于Windows来说,没有太大的不同。从这里举一个例子,您只将*.cpp您的方法包含在extern "C"
诸如
extern "C"
{
      __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);
      }
}
然后编译,然后在您的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);
            }
    }