Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xliff/4d83cd0476d39d2ebce0d77884d7c6e3 to your computer and use it in GitHub Desktop.
Save Xliff/4d83cd0476d39d2ebce0d77884d7c6e3 to your computer and use it in GitHub Desktop.
Extracting Data from a C Array using NativeCall

I have the following definition from C:

const SlopeSample slope_sampler_pi_samples_array[] = {
    {0.0 * G_PI, "0"},     {0.5 * G_PI, "π/2"},   {1.0 * G_PI, "π"},
    {1.5 * G_PI, "3π/2"},  {2.0 * G_PI, "2π"},    {2.5 * G_PI, "5π/2"},
    {3.0 * G_PI, "3π"},    {3.5 * G_PI, "7π/2"},  {4.0 * G_PI, "4π"},
    {4.5 * G_PI, "9π/2"},  {5.0 * G_PI, "5π"},    {5.5 * G_PI, "11π/2"},
    {6.0 * G_PI, "6π"},    {6.5 * G_PI, "13π/2"}, {7.0 * G_PI, "7π"},
    {7.5 * G_PI, "15π/2"}, {8.0 * G_PI, "8π"},    {8.5 * G_PI, "17π/2"},
    {9.0 * G_PI, "9π"},    {9.5 * G_PI, "19π/2"}, {10.0 * G_PI, "20π"}};

const SlopeSample *const slope_sampler_pi_samples =
slope_sampler_pi_samples_array;

Which tells me I should be able to pick this data up using the slope_sampler_pi_samples from a library.

Now, as I understand it, I should be able to use cglobal to pick up this data, and indeed. I can get what appears to be a pointer from NativeCall:

my $month_samples := cglobal(
  slope, 'slope_sampler_month_samples', Pointer
);

# OUTPUT: NativeCall::Types::Pointer<0x7fc69fe9edb8>

However, when I try and extract anything from the array, I get a SEGV.

# Try to extract the third element.
my $month_samples := cglobal(
  slope, 'slope_sampler_month_samples', Pointer
);
nativecast(SlopeSample, Pointer.new($month_samples + 2 * nativesizeof(SlopeSample))

# OUTPUT: SEGV

What am I doing wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment