Search code examples
c#.net-corepinvoke

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


I am coding a sample to use c# code to call some function in c++ shared library. The environment is Ubuntu 16.04 and .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);

            }
        }

the cpp:

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

If I run the c# code, I get the error message:

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

I think the compiler may change the name of the function so it can't be found. How to fix it?


Solution

  • You need to mark your C++ function as extern "C" so that the .NET Core runtime can find the function name.