Skip to content

Instantly share code, notes, and snippets.

@nassor
Forked from andrewloable/Program.cs
Created May 5, 2021 15:55
Show Gist options
  • Save nassor/792644af41dbd27eabeda83a5d139480 to your computer and use it in GitHub Desktop.
Save nassor/792644af41dbd27eabeda83a5d139480 to your computer and use it in GitHub Desktop.
Use a library compiled in Go in c# (.net)
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace GoSharedDLL
{
class Program
{
[DllImport("shared.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr ReturnReversedString(byte[] input);
static void Main(string[] args)
{
var input = Encoding.UTF8.GetBytes("Hello World!");
var resultbytes = ReturnReversedString(input);
var output = Marshal.PtrToStringAnsi(resultbytes);
Console.WriteLine(output);
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
}
}
package main
import "C"
//export ReturnReversedString
func ReturnReversedString(input *C.char) *C.char {
str := C.GoString(input)
runes := []rune(str)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
retval := string(runes)
return C.CString(retval)
}
func main() {}
// compile using go build -o shared.dll -buildmode=c-shared
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment