我想在C#的包装类中使用这段C代码。我有一个带有各种参数的结构,包括一个结构和函数指针。
C代码:
struct wiringPiNodeStruct
{
int pinBase ;
int pinMax ;
int fd ; // Node specific
unsigned int data0 ; // ditto
void (*pinMode) (struct wiringPiNodeStruct *node, int pin, int mode) ;
struct wiringPiNodeStruct *next ;
} ;我尝试编组上面的代码。但是我无法为包含结构和结构中的结构的函数指针找到合适的解决方案。
C#代码:
[StructLayout(LayoutKind.Sequential)]
public struct wiringPiNodeStruct
{
public int pinBase;
public int pinMax;
public int fd; // Node specific
public uint data0; // ditto
public delegate void pinMode (struct wiringPiNodeStruct IntPtr node, int pin, int mode) ;
public struct wiringPiNodeStruct *next ;
};发布于 2016-11-09 17:14:03
不管你以前用过链表,还是没用过…这里只有一个结构,其中有一个字段指向它的“继承者”。当然,我不能保证我建议的解决方案在不修改的情况下就能工作;但我已经使用过很多次P/Invoke,所以我会尝试这样的方法……至少,它会给你一个想法,希望如此。
为简单起见(并去掉一些编组魔术),我将pinMode和next声明为IntPtr字段;请记住,IntPtr在32位和64位中有不同的大小。确保托管部分和非托管部分使用相同的位数...
delegate void pinMode (IntPtr node, int pin, int mode);
[StructLayout(LayoutKind.Sequential)]
internal struct wiringPiNodeStruct
{
public int pinBase;
public int pinMax;
public int fd;
public uint data0;
public IntPtr pinMode;
public IntPtr next
};您可能会面临两种情况:一种是只需要读取和处理结构,另一种是希望创建并将其传递给非托管代码。让我们看看阅读部分;迭代列表可能看起来像这样…
wiringPiNodeStruct node = ...
while (node.next != IntPtr.Zero)
{
wiringPiNodeStruct next;
next = (wiringPiNodeStruct) Marshal.PtrToStructure(
node.next,
typeof(wiringPiNodeStruct));
...
node = next;
}如果你想/需要调用pinMode函数,你可以尝试这样做...
wiringPiNodeStruct node = ...
wiringPiNodeStruct next = (wiringPiNodeStruct) Marshal.PtrToStructure(
node.next,
typeof(wiringPiNodeStruct));
pinMode func = (pinMode) Marshal.GetDelegateForFunctionPointer(
next.pinMode,
typeof(pinMode));
func(node.next, 0, 0);现在让我们创建一个结构;这当然是一个非常简单的例子……您可以创建一些辅助实用程序,这些实用程序可以从可枚举的数据源创建链表结构-还可以跟踪分配的内存,并在不再需要时适当地释放非托管内存。
var second = new wiringPiNodeStruct { };
int size = Marshal.SizeOf(typeof(wiringPiNodeStruct));
IntPtr pSecond = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(second, pSecond, true);
pinMode func = new pinMode((ptr, pin, mode) => { });
var first = new wiringPiNodeStruct { };
first.pinMode = Marshal.GetFunctionPointerForDelegate(func);
first.next = pSecond;如果非托管部件将pinMode用作回调,请确保func与存储在pinMode字段中的指针具有相同的生存期。
您也可以尝试使用wiringPiNodeStruct类型的不同声明;有时,使用为读取或写入量身定做的声明更容易……
https://stackoverflow.com/questions/38868578
复制相似问题