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

Hea*_*ker 4 c# pinvoke .net-core

我正在编写一个示例以使用 c# 代码调用 c++ 共享库中的某些函数。环境为 Ubuntu 16.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);

            }
        }
Run Code Online (Sandbox Code Playgroud)

中央人民政府:

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

如果我运行 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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ich 5

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