I have a C++ project written in Linux, now my goal is to make this project call from .NET Core and still run in Linux, just like using DLL ( Dynamic-link library ) from .NET.
The difficulty is that DLL designs for Windows, even though I can create DLL in Visual Studio 2019, I can't use the DLL in Linux. I need to build a shared library for .NET Core in Linux.
First, I implemented these two articles:
Building a cross-platform C++ library to call from .NET Core
Calling a cross-platform C++ library from .NET Core
However, I have some problems:
(1) I need to link other header files, so I cannot just use CMake to get shared library(so file) as the Building article above.
Sol: I use g++ to get the shared library, and add EntryPoint when DllImport in Program.cs .
使用 gcc 自製 C/C++ 靜態、共享與動態載入函式庫教學
Create shared library from cpp files and static library with g++ [duplicate]
Example: The library.cpp will include the file1.h, file2.h, file3.h
g++ -fPIC -c -o file1.o file1.cpp
g++ -fPIC -c -o file2.o file2.cpp
g++ -fPIC -c -o file3.o file3.cpp
g++ -fPIC -std=c++11 -c -o library.o library.cpp
gcc -shared -Wl,-soname,libTestLib.so.1 -o libTestLib.so.1.0.0 library.o file1.o file2.o file3.o
objdump -p libTestLib.so.1.0.0 | grep SONAME
ln -s libTestLib.so.1.0.0 libTestLib.so
ln -s libTestLib.so.1.0.0 libTestLib.so.1
export "LD_LIBRARY_PATH=$PATH:/usr/local/lib"
cp libTestLib.so* /usr/local/lib/
cp libTestLib.so /CoreNativeTest
(2) I use other shared libraries, such as re2, so we need to reinstall the library with -fPIC and copy the so files to CoreNativeTest
Sol:
(2-1) In CoreNativeTest.csproj, add EmbeddedResource if needing to include more so files, and add PackageReference if needing to use other packages.
(2-2) In Program.cs, add new variables like var libManager to LoadNativeLibrary.
(3) In C# (.NET Core), I pass the strings to function, and I want to get a string output.
Sol: Passing strings from C# to C++ DLL and back — minimal example
(3-1) In C++, the parameters function are char*, whether they will get string type or StringBuilder type.
And notice the problem of char* to string or string to char*.
(3-2) In C#, System.Text.StringBuilder could get the changed string from C++ to C#.
(4) Before dotnet build and dotnet run, make sure to copy all shared libraries used to CoreNativeTest, and specify the library path.
Sol:
export "LD_LIBRARY_PATH=$PATH:/usr/local/lib"
dotnet build
dotnet run
