Skip to main content
 首页 » 编程设计

python之如何将指向 Python cffi 结构的指针转换为 System.IntPtr (.NET)

2025年05月04日22jirigala

我需要将 System.IntPtr 传递给 .NET 函数(Python 和 pythonnet)。此指针应引用在 cffi 中创建的结构。

我找到了 this :

from CLR.System import IntPtr, Int32 
i = Int32(32) 
p = IntPtr.op_Explicit(i) 

这是我目前尝试过的

import clr 
from cffi import FFI 
 
ffi = FFI() 
 
custom_t = ''' 
            typedef struct 
            { 
                float x; 
                 float y; 
                 float z; 
 
            } float3; 
            ''' 
 
ffi.cdef(custom_t) 
 
cfloat3 = ffi.new("float3 *") 
cfloat3.x = 1.0 
cfloat3.y = 2.0 
cfloat3.z = 3.0 
print(cfloat3) 
 
from System import IntPtr 
 
p = IntPtr.op_Explicit(id(cfloat3)) #works, sort of... 
print(p) 
 
#I would rather see something like 
p2 = IntPtr.op_Explicit(ffi.addressof(cfloat3).value) 
p3 = IntPtr(ffi.cast("float3*", cfloat3)) 
p4 = IntPtr(ffi.cast("void3*", cfloat3)) 
 
#type(_), ffi.typeof(_), ffi.typeof(_).kind, ffi.addressof() 

但我不确定是否使用 IntPtr.op_Explicit是最好的解决方案。它看起来有点像与 id() 结合使用的解决方法,我很确定有更好的解决方案。

请您参考如下方法:

Python.Net 内部不直接支持 CFFI,反之亦然,因此您需要将指针从一个库转换为一个整数,然后将该整数重新导入另一个库。

在 CFFI 中,intaddr = ffi.cast("intptr_t", p) 会给你一个整数。然后你可能会做IntPtr(intaddr)。