如何在ffi中使用它

时间:2018-08-24 08:22:43

标签: assembly lua jit luajit

std::string __cpuid()
{
    char VendorName[49] = {0};
    char VendorID[13] = {0};
    unsigned int a, b, c, d;
__asm xor EBX, EBX;
__asm xor ECX, ECX;
__asm xor EDX, EDX;
__asm mov EAX, 0x80000002;
__asm cpuid;
__asm mov a, EAX;
__asm mov b, EBX;
__asm mov c, ECX;
__asm mov d, EDX;
__asm mov DWORD PTR [VendorName + 0], EAX;
__asm mov DWORD PTR [VendorName + 4], EBX;
__asm mov DWORD PTR [VendorName + 8], ECX;
__asm mov DWORD PTR [VendorName + 12], EDX;
__asm mov EAX, 0x80000003;
__asm cpuid;
__asm mov DWORD PTR [VendorName + 16], EAX;
__asm mov DWORD PTR [VendorName + 20], EBX;
__asm mov DWORD PTR [VendorName + 24], ECX;
__asm mov DWORD PTR [VendorName + 28], EDX;
__asm mov EAX, 0x80000004;
__asm cpuid;
__asm mov DWORD PTR [VendorName + 32], EAX;
__asm mov DWORD PTR [VendorName + 36], EBX;
__asm mov DWORD PTR [VendorName + 40], ECX;
__asm mov DWORD PTR [VendorName + 44], EDX;
__asm mov EAX, 0x00000000;
__asm cpuid;
__asm mov DWORD PTR [VendorID + 0], EBX;
__asm mov DWORD PTR [VendorID + 4], EDX;
__asm mov DWORD PTR [VendorID + 8], ECX;
__asm mov EAX, 0x80000004;
    strcat(VendorName, " ");
    strcat(VendorName, VendorID);
    return string(VendorName);
}

先生,如何在ffi lua中使用它?我对ffi不好

我尝试使用ffi.cdef,但是编译器问我:声明说明符应在'std'附近

我试图使用很多东西,但我是菜鸟

1 个答案:

答案 0 :(得分:1)

此代码可在LuaJIT x86上运行
(如果LuaJIT是使用MS VisualStudio构建的,请使用MinGW,则无效)

assert(jit.arch =='x86')

local ffi = require("ffi")
local qwords = ffi.typeof("uint64_t[?]")
local dwords = ffi.typeof("uint32_t *")
-- cpuid_EAX_EDX = push EBX / cpuid / pop EBX / ret
local cpuid_EAX_EDX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x5B\xC3")
-- cpuid_EBX_ECX = push EBX / cpuid / xchg EAX,ECX / xchg EAX,EDX / xchg EAX,EBX / pop EBX / ret
local cpuid_EBX_ECX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x91\x92\x93\x5B\xC3")

local function cpuid(n)
   local arr = ffi.cast(dwords, qwords(2, cpuid_EAX_EDX(n), cpuid_EBX_ECX(n)))
   return ffi.string(arr, 4), ffi.string(arr + 2, 4), ffi.string(arr + 3, 4), ffi.string(arr + 1, 4)
end

local s1 = ""
for n = 0x80000002, 0x80000004 do
   local eax, ebx, ecx, edx = cpuid(n)
   s1 = s1..eax..ebx..ecx..edx
end
s1 = s1:gsub("^%s+", ""):gsub("%z+$", "")  -- remove leading spaces and trailing zeroes

local eax, ebx, ecx, edx = cpuid(0)
local s2 = ebx..edx..ecx
s2 = s2:gsub("^%s+", ""):gsub("%z+$", "")  -- remove leading spaces and trailing zeroes

print(s1.." "..s2)  -- Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz GenuineIntel