Skip to content

Instantly share code, notes, and snippets.

@andrewloable
Created June 23, 2019 05:48
Show Gist options
  • Save andrewloable/afa1c683701cec18c4530f6a91692e0b to your computer and use it in GitHub Desktop.
Save andrewloable/afa1c683701cec18c4530f6a91692e0b 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
@MichaelSkirda
Copy link

MichaelSkirda commented Mar 19, 2024

You should mark exporting method with comment above
//export [Some name]
No space after //

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment