go dllmain


go 编译dll,实现dllmain

main.go

package main

/*
#include "dllmain.h"
*/
import "C"

import (
	"fmt"
)
//export exfunc
func exfunc() {
	//set GOARCH=386

	//set GOARCH=amd64
	//set CGO_ENABLED=1
	//go build -o dlltest.x64.dll -buildmode=c-shared
	fmt.Println("dll exfunc")
}
func main() {
	// nothing really. xD
}

dllmain.h

#ifndef M_DLLMAIN_H
#define M_DLLMAIN_H

#include <windows.h>

BOOL WINAPI DllMain(
    HINSTANCE _hinstDLL,  // handle to DLL module
    DWORD _fdwReason,     // reason for calling function
    LPVOID _lpReserved    // reserved
);

#endif

dllmain.c

#include "dllmain.h"

extern void exfunc();//main.go export function


DWORD WINAPI MyThreadFunction(LPVOID lpParam) {
	exfunc();//c call go
    return 0;
}

BOOL WINAPI DllMain(
    HINSTANCE _hinstDLL,  // handle to DLL module
    DWORD _fdwReason,     // reason for calling function
    LPVOID _lpReserved)   // reserved
{
    switch (_fdwReason) {
	case DLL_PROCESS_ATTACH:
		// Initialize once for each new process.
        // Return FALSE to fail DLL load.
        {
            HANDLE hThread = CreateThread(NULL, 0, MyThreadFunction, 0, 0, NULL);
            // CreateThread() because otherwise DllMain() is highly likely to deadlock.
        }
        break;
    case DLL_PROCESS_DETACH:
        // Perform any necessary cleanup.
        break;
    case DLL_THREAD_DETACH:
        // Do thread-specific cleanup.
        break;
    case DLL_THREAD_ATTACH:
		// Do thread-specific initialization.
        break;
    }
    return TRUE; // Successful.
}

参考链接

how-to-implement-dllmain-entry-point-in-go

Go项目反射改造
cgo 的一些坑和注意事项

posted @ 2023-08-01 10:18  DirWangK  阅读(24)  评论(0编辑  收藏  举报