在 Linux 中从 C# .net 核心控制台调用 C++ 共享库

call C++ shared library from C# .net core console in Linux

我正在编写示例以使用 C# 代码调用 C++ 共享库中的某些函数。环境是Ubuntu16.04和.NET Core 2.0.

       class Program
       {
           [DllImport("libc.so.6")]
            private static extern int getpid();           
           [DllImport("/home/xxx/invoke/hi.so")]
            private static extern int Sayhi();

           static void Main(string[] args)
           {
            int pid= getpid();
            Console.WriteLine(pid);
            Console.WriteLine("Hello World!");
            int status= Sayhi();
            Console.WriteLine(status);

            }
        }

菲律宾共产党:

#include <iostream>
using namespace std;
int Sayhi(){
cout<<"hello world from cpp!"<<endl;
return 1;
}

如果我 运行 c# 代码,我收到错误消息:

Unhandled Exception: System.EntryPointNotFoundException: Unable to find an entry point named 'Sayhi' in DLL '/home/xxx/invoke/hi.so'.
   at invoke.Program.Sayhi()
   at invoke.Program.Main(String[] args) in /home/xxx/invoke/Program.cs:line 17

我认为编译器可能会更改函数的名称,因此无法找到它。如何解决?

您需要将您的 C++ 函数标记为 extern "C",以便 .NET Core 运行时可以找到函数名称。