// echo.c 源文件 ------------------------------------ #include <stdio.h>#define DLLOBJECT __declspec(dllexport)DLLOBJECT void writeln(char *s) { printf("%s\n", s); } // echo.cs 源文件, 调用上面的 c code dll ------------------------------- using System; using System.Runtime.InteropServices;namespace HelloUtil { public class Echo { [DllImport("echo.native.dll", CallingConvention = CallingConvention.Cdecl)] static extern void writeln(string s); string myString; public Echo(string aString) { myString = aString; } public void Tell() { Console.WriteLine(myString); } } }// 主文件 hello.cs -------------------------------- using System; using HelloUtil;public class Hello { public static void Main() { Echo h = new Echo("Hello my 1st C# object !"); h.Tell(); } }编译方法: 从开始菜里里找到 "Visual Studio 2005 命令提示" 或者 "Visual Studio 2003 命令提示" 进入其中, 主要是为了得到编译环境, 转到 hello.cs 等文件所在目录, 依次输入下面的命令: csc /nologo /t:library /out:echo.dll echo.cs csc /nologo /out:hello.exe /r:echo.dll hello.cs gcc -shared -o echo.native.dll echo.c strip echo.native.dll运行: 到 hello.cs 文件所在目录, 输入 hello 观察结果.
在C#中调用一个API同在VB中调用API一样。我们应该知道API的DLL名称,并且使用sysimport引入它。下面这个例子显示了如何调用MessageBox API: using System.Runtime.InteropServices; class callAPICls { [DllImport("User32.dll")] public static extern int MessageBoxA(int h, string m, string c, int type); public static int Main(){ return MessageBoxA(0, "Hello World!", "Caption", 0); } }将函数名字和引入的dll换成你要调用的即可
#include <stdio.h>#define DLLOBJECT __declspec(dllexport)DLLOBJECT void writeln(char *s)
{
printf("%s\n", s);
}
// echo.cs 源文件, 调用上面的 c code dll -------------------------------
using System;
using System.Runtime.InteropServices;namespace HelloUtil
{
public class Echo
{
[DllImport("echo.native.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void writeln(string s);
string myString; public Echo(string aString)
{
myString = aString;
} public void Tell()
{
Console.WriteLine(myString);
}
}
}// 主文件 hello.cs --------------------------------
using System;
using HelloUtil;public class Hello
{
public static void Main()
{
Echo h = new Echo("Hello my 1st C# object !");
h.Tell();
}
}编译方法:
从开始菜里里找到 "Visual Studio 2005 命令提示" 或者 "Visual Studio 2003 命令提示"
进入其中, 主要是为了得到编译环境, 转到 hello.cs 等文件所在目录, 依次输入下面的命令:
csc /nologo /t:library /out:echo.dll echo.cs
csc /nologo /out:hello.exe /r:echo.dll hello.cs
gcc -shared -o echo.native.dll echo.c
strip echo.native.dll运行:
到 hello.cs 文件所在目录, 输入 hello 观察结果.
class callAPICls {
[DllImport("User32.dll")]
public static extern int MessageBoxA(int h, string m, string c, int type);
public static int Main(){
return MessageBoxA(0, "Hello World!", "Caption", 0);
}
}将函数名字和引入的dll换成你要调用的即可