如何将指向Python cffi结构的指针转换为系统接口(.NET)?

2024-09-23 10:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我要通过一个系统接口到.NET函数(pythonnet的pythonnet)。此指针应该引用在cffi中创建的结构。在

我找到了this

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

这就是我目前所做的

^{pr2}$

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


Tags: 函数fromnet系统解决方案thiscffi结构
3条回答

内部没有对CFFI的直接支持Python.Net反之亦然,因此需要将指针从一个库强制转换为整数,然后将该整数重新导入到另一个库中。在

从CFFI,intaddr = ffi.cast("intptr_t", p)将给您一个整数。那么你可以做IntPtr(intaddr)。在

解决方法是使用Overloads方法IntPtr

from System import IntPtr, Int32, Int64
my_ptr = ffi.cast("intptr_t", my_c_struct)
cs_handle = IntPtr.Overloads[Int64](Int64(int(my_ptr)))

如前所述here和{a2}。在

下面是一个工作示例:

^{pr2}$

关于上面发生的事情的更多信息(可以在这里找到):

  • C#'s IntPtr maps exactly to C/C++'s intptr_t.

  • intptr_t integer type capable of holding a pointer

  • To cast a pointer to an int, cast it to intptr_t or uintptr_t, which are defined by C to be large enough integer types. cffi doc with examples

  • IntPtr is just a .NET type for void*.

  • The equivalent of an unmanaged pointer in the C# language is IntPtr. You can freely convert a pointer back and forth with a cast. No pointer type is associated with it even though its name sounds like "pointer to int", it is the equivalent of void* in C/C++.

  • IntPtr(5) complains that int/long' value cannot be converted to System.IntPtr. It seems like it is trying to cast or something instead of calling the constructor. (found here)

  • Methods of CLR objects have an '_ overloads _', which will soon be deprecated in favor of iPy compatible Overloads, attribute that can be used for this purpose. (found here)

相关问题 更多 >