由于类型从 C 转换为 C++,无法编译错误 C2440

Unable to compile with Error C2440 due to type cast from C to C++

本文关键字:C++ 编译 C2440 错误 转换 于类型 类型      更新时间:2023-10-16
inline BOOL FupVmCall(ULONG_PTR hypercall_number, void *context) {
#pragma section(".asm", read, execute)
__declspec(allocate(".asm")) static const BYTE CODE[] = {
0x0F, 0x01, 0xC1, //    vmcall
0x74, 0x0E,       //    jz      short errorWithCode
0x72, 0x04,       //    jb      short errorWithoutCode
0x48, 0x33, 0xC0, //    xor     rax, rax
0xC3,             //    retn
// errorWithoutCode:
0x48, 0xC7, 0xC0, 0x02, 0x00, 0x00, 0x00, //    mov     rax, 2
0xC3,                                     //    retn
// errorWithCode:
0x48, 0xC7, 0xC0, 0x01, 0x00, 0x00, 0x00, //    mov     rax, 1
0xC3,                                     //    retn
};
typedef unsigned char(__stdcall * AsmVmxCallType)(
_In_ ULONG_PTR hypercall_number, _In_opt_ void *context);
#pragma warning(suppress : 4055)
AsmVmxCallType AsmVmxCall = (AsmVmxCallType)CODE;
__try {
return AsmVmxCall(hypercall_number, context) == 0;
} __except (EXCEPTION_EXECUTE_HANDLER) {
SetLastError(GetExceptionCode());
return FALSE;
}
}

我正在尝试使用 VS2019 从C++项目中编译上述代码

如果我将主文件更改为main.c,它可以毫无问题地编译

但是,如果我将其更改为main.cpp,则会出现C2440类型的转换问题。

C2440   'type cast': cannot convert from 'const BYTE [27]' to 'AsmVmxCallType'
AsmVmxCallType AsmVmxCall = (AsmVmxCallType)CODE;

我什至试图用extern "C"包裹,但没有解决问题。

如何制作此类型转换?

您可以先将CODE强制转换为 void 指针,然后将其强制转换为函数指针:

AsmVmxCallType AsmVmxCall = (AsmVmxCallType)(void *)CODE;