Skip to content

Instantly share code, notes, and snippets.

@totomz
Created May 27, 2021 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totomz/eb11223739659153f7271a8086c3b6b6 to your computer and use it in GitHub Desktop.
Save totomz/eb11223739659153f7271a8086c3b6b6 to your computer and use it in GitHub Desktop.
Calling Go from C++
// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <windows.h>
#include <iostream>
//typedef char* (__stdcall* f_funci)();
typedef char* (__stdcall* f_PrintZio)(char*);
int main()
{
std::cout << "Hello World!\n";
HINSTANCE hGetProcIDDLL = LoadLibrary(L"C:\\Users\\zione\\Desktop\\shared\\midly.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
// resolve function address here
//f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "PrintSetteSette");
//f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "PrintStr");
f_PrintZio funci = (f_PrintZio)GetProcAddress(hGetProcIDDLL, "PrintZio");
if (!funci) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
std::cout << "funci() returned " << funci((char*)"All the small things, true care, true thingsa") << std::endl;
std::cout << "Zio!!\n";
}
package main
import "C"
import "fmt"
//export PrintSetteSette
func PrintSetteSette() int {
return 77
}
//export PrintStr
func PrintStr() *C.char{
return C.CString(fmt.Sprintf("From DLL: Hello, %s!\n", 8))
}
//export PrintZio
func PrintZio(Input *C.char) *C.char{
return C.CString(fmt.Sprintf("From DLL: zio, %s", C.GoString(Input)))
}
func main() {
// Need a main function to make CGO compile package as C shared library
}
// build with go build -buildmode=c-shared -o midly.dll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment