我试图将一个函数指针传递给LLVM解释器,但是当我在llvm函数中打印它时,它为null。我正在使用C API。
以下是相关代码(在D中):
extern (C) void hello() {
import core.stdc.stdio : printf;
printf("Hello there!");
}
private void testFunctionPass() {
auto printfType = LLVMFunctionType(LLVMInt32Type(),
[LLVMPointerType(LLVMInt8Type(), 0)].ptr, 1, 1);
auto llvmPrintf = LLVMAddFunction(moduleBuilder.module_, "printf", printfType);
auto passedType = LLVMFunctionType(LLVMVoidType(), null, 0, 0);
auto passedPtrType = LLVMPointerType(passedType, 0);
auto testFunctionType = LLVMFunctionType(LLVMVoidType(), &passedPtrType, 1, 0);
auto testFunction = LLVMAddFunction(moduleBuilder.module_, "fp_pass_test", testFunctionType);
auto entryBlock = LLVMAppendBasicBlock(testFunction, "entry");
auto builder = LLVMCreateBuilder();
auto paramValue = LLVMGetParam(testFunction, 0);
LLVMPositionBuilderAtEnd(builder, entryBlock);
auto pointerPrintFormat = LLVMBuildGlobalStringPtr(builder, "received ptr: %x\n", "");
LLVMBuildCall(builder, llvmPrintf, [pointerPrintFormat, paramValue].ptr, 2, "");
LLVMBuildCall(builder, paramValue, null, 0, "");
LLVMBuildRetVoid(builder);
LLVMDisposeBuilder(builder);
LLVMVerifyModule(moduleBuilder.module_, LLVMPrintMessageAction, null);
LLVMDumpValue(testFunction);
void* passedPtr = &hello;
LLVMGenericValueRef passedPtrGeneric = LLVMCreateGenericValueOfPointer(passedPtr);
auto unwrapped = LLVMGenericValueToPointer(passedPtrGeneric);
import core.stdc.stdio : printf;
printf("passed ptr: %x\n", passedPtr);
printf("unwrapped ptr: %x\n", unwrapped);
LLVMRunFunction(interpreter, testFunction, 1, &passedPtrGeneric);
}
这是输出:
define void @fp_pass_test(void ()*) {
entry:
%1 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([18 x i8], [18 x i8]* @0, i32 0, i32 0), void ()* %0)
call void %0()
ret void
}
passed ptr: 4142ddb0
unwrapped ptr: 4142ddb0
received ptr: 0
Program exited with code -11
有人知道为什么指针通过LLVMRunFunction传递后会变为空吗?