How to define fixed-length strings in a Perl6 NativeCall struct?

天大地大妈咪最大 提交于 2019-12-23 08:37:36

问题


I have a third-party C library that defines a struct similar to:

struct myStruct {
  int a;
  int b;
  char str1[32];
  char str2[32];
};

And a function that takes a pointer to this struct and populates it. I need my Perl6 native call to provide that struct, and then read the results.

So far I've got the struct defined in Perl6 as:

class myStruct is repr('CStruct') {
  has int32 $.a;
  has int32 $.b;
  has Str $.str1; # Option A: This won't work as Perl won't know what length to allocate
  has CArray[uint8] $.str2; # Option B: This makes more sense, but again how to define length?  
                     # Also, would this allocate the array in place, or 
                     #    reference an array that is separately allocated (and therefore not valid)?
}

And a native call like:

sub fillStruct(myStruct) is native('test_lib') { ... }
my $struct = myStruct.new();
fillStruct($struct); # Gives a seg fault with any variation I've tried so far

How can I make this work?


回答1:


As others have said, there does not appear to be any way to achieve this at present.

I've resorted to defining a new C function(s) as a workaround. The function effectively acts as an accessor method returning just the fields that I need as discrete NativeCall-friendly pointers.

Hopefully the community will get to implementing proper support for this case at some point.




回答2:


At the time of writing, this doesn't seem to be handled.
As a workaround, my take would be to let a macro generate 32 int8, adequately placing field names.



来源:https://stackoverflow.com/questions/46481221/how-to-define-fixed-length-strings-in-a-perl6-nativecall-struct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!