1 回答
TA贡献1820条经验 获得超9个赞
它与我一起工作如下:
第一步:编写go代码:
// main.go
package main
import "C"
import "fmt"
//export HelloWorld
func HelloWorld() {
fmt.Printf("hello world from GO\n")
}
func main() {}
// compile the code as:
// go build -ldflags="-s -w" -buildmode=c-shared -o libgo.dll main.go
第 2 步:将 C# 代码编写为:
// main.cs
using System;
using System.Runtime.InteropServices;
public class MainClass
{
[DllImport("libgo.dll")]
public static extern void HelloWorld(); // function signature, must have a return type
static void Main()
{
HelloWorld();
}
}
// compile as:
// open:
// Visual Studio x64 Native Tools Command Prompt
// csc -platform:x64 cm.cs
第三步:编译这两个文件,从编译go文件开始
第四步:运行可执行文件:
更新
去文件:
// main.go
package main
import (
"fmt"
)
// The import "C" should come directly after the // #include ..., i.e. no empty lines allowed,
// if there are empty lines, the compliler will read the // #include as normal comment, not as C import
/*
#include <stdlib.h>
*/
import "C"
//export GetHello
func GetHello(Input *C.char) *C.char {
cStr := C.CString(fmt.Sprintf("From DLL: Hello, %s!\n", C.GoString(Input)))
// C.free(unsafe.Pointer(cStr))
return cStr
}
func main() {}
// compile the code as:
// go build -ldflags="-s -w" -buildmode=c-shared -o libgo.dll main.go
C#文件:
// main.cs
using System;
using System.Text;
using System.Runtime.InteropServices;
public class MainClass
{
[DllImport("libgo.dll", CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetHello(byte[] data);
static string CallDll(string name) {
IntPtr output= IntPtr.Zero;
var a = GetHello(Encoding.UTF8.GetBytes(name));
return "GetHello Returns: " + Marshal.PtrToStringAnsi(a);
}
static void Main()
{
Console.WriteLine(CallDll("Ahmad"));
}
}
// compile as:
// open:
// Visual Studio x64 Native Tools Command Prompt
// csc -platform:x64 main.cs
这是一个使用字符串的示例:
- 1 回答
- 0 关注
- 927 浏览
添加回答
举报