-->

How to define fixed-length strings in a Perl6 Nati

2019-06-18 09:58发布

问题:

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.