我意识到将 exe 视为 dll 比我想象的要复杂得多。我最终得到了以下解决方法。
Python
import numpy as np
import ctypes as C
lib = C.cdll.LoadLibrary('pycon.exe')
lib.init( C.windll.kernel32.GetProcAddress( C.windll.msvcrt._handle,'printf'))
d = np.ones((5)).astype('double')
lib.fun(d.ctypes.data_as(C.POINTER(C.c_double)), C.c_size_t(5))
C
#include <stdio.h>
#include <math.h>
int (*pyprintf)(const char *,...) =0;
extern "C" __declspec(dllexport)
void fun(double *datav, size_t size) {
double * data = (double *) datav;
int i;
for (i = 0; i < size; ++i)
{
data[i] = 1.7159*tanh(0.66666667*data[i]);
pyprintf("workign! %f\n",data[i]);
}
}
extern "C" __declspec(dllexport)
void init(int (*_printfPtr)(const char *,...)) {
pyprintf=_printfPtr;
}
int main(int argc, char* argv[])
{
printf("exe");
return 0;
}
编辑
好奇心已经战胜了我,兔子洞越来越大,现在它比上面的笨拙了一点,似乎可以同时作为 exe 和 dll 运行,并且加载代码更多。
要求
- 'exe' 必须只依赖于 kernel32
- pefile 包
- 链接器标志
/FIXED:NO -entry:_DllMainCRTStartup@12
Python
import numpy as np
import ctypes as C
import pefile
def unprotect( address):
crap = C.byref(C.create_string_buffer("\x00"*4))
res = C.windll.kernel32.VirtualProtect(address, 0x1000, 0x40, crap)
lib = C.cdll.LoadLibrary('pycon.exe')
k32 = C.windll.kernel32
pe = pefile.PE('pycon.exe')
for entry in pe.DIRECTORY_ENTRY_IMPORT:
#print entry.dll
#assuming that the exe only has dependency on kernel32
for imp in entry.imports:
diff = imp.address-0x400000
memptr = k32.GetProcAddress(k32._handle,imp.name)
unprotect(lib._handle+diff)
fptr = (C.c_uint).from_address(lib._handle+diff)
fptr.value = memptr
d = np.ones((5)).astype('double')
lib.init()
lib.fun(d.ctypes.data_as(C.POINTER(C.c_double)), C.c_size_t(5))
print d
C
#include <stdio.h>
#include <math.h>
#include <windows.h>
extern "C" BOOL WINAPI _CRT_INIT(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);
extern "C" __declspec(dllexport)
void fun(double *datav, size_t size) {
double * data = (double *) datav;
int i;
for (i = 0; i < size; ++i)
{
data[i] = 1.7159*tanh(0.66666667*data[i]);
printf("workign! %f\n",data[i]);
}
fflush(stdout);
}
extern "C" __declspec(dllexport)
void init() {
_CRT_INIT(NULL,DLL_PROCESS_ATTACH,NULL);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
_CRT_INIT(NULL,DLL_PROCESS_ATTACH,NULL);
printf("main exe");
return TRUE;
}