I have written a short article: [Popular Science essay] Calling C language functions in C #. It is an example of Microsoft. Net in Windows. Today we will provide another small example, which is based on Mono on the Linux platform. The specific technology P/Invoke For Calling C language functions in C # is described in the previous article [Popular Science short text] Calling C language functions in C, readers who do not know about it can take a look at it. here we will not discuss it much. Let's take a look at our example.
I. Prepare a dynamic link library
C language source code: Test. c is consistent with the Code on the previous Windows platform:
int sum(int a, int b) { return a + b; }
We use gcc to compile it into a dynamic link library libtest. so
gcc -c -Wall -Werror -fpic Test.cgcc -shared -o libtest.so Test.o
In this way, we get the dynamic link library libtest. so.
No picture, no truth. Let's take a look:
II,Call the sum () method in Test. dll through P/Invoke in C #
We use vi to compile a simple C # program: Invoke. cs
This C # program has only six lines of code except comments, namespace definitions, and references:
// ----------------------------------------------------------------------- // <copyright file="Invoke.cs" company="Yaping Xin"> // P/Invoke example. // </copyright> // -----------------------------------------------------------------------namespace Invoke { using System; using System.Runtime.InteropServices; /// <summary> /// .Net P/Invoke example. /// </summary> internal class Program { /// <summary> /// Entry point of the application. /// </summary> /// <param name="args">Console arguments.</param> internal static void Main(string[] args) { int result = Sum(2, 3); Console.WriteLine("Shared library func execute result: {0}", result); } /// <summary> /// Call method int sum(int, int) defined in Test.dll /// </summary> /// <param name="a">parameter a</param> /// <param name="b">parameter b</param> /// <returns>sum of a and b</returns> [DllImport("libtest.so", EntryPoint = "sum")] private static extern int Sum(int a, int b); } }
Compile the C # source file in the command line:
gmcs Invoke.cs
In this way, an executable mono-based file Invoke.exe is compiled.
Iii. Execution
Copy libtest. so to the/lib directory so that our program can find it. Why put it in this directory? This is based on the Linux operating system's search for dynamic link library rules. If you want to explain this problem in detail, please read the Linux system documentation and manual.
Execute our C # code to compile the executable file:
mono Invoke.exe
The execution result is the same as that in [Popular Science short text] Calling C language functions in C:
Shared library func execute result: 5
No picture, no truth, let's take another one:
Related links:
- Interop with Native Libraries
Http://www.mono-project.com/Interop_with_Native_Libraries
- Dynamic library (. so)
Http://linux-wiki.cn/wiki/zh-hans/%E5%8A%A8%E6%80%81%E5%BA%93%28.so%29