Home Ask Login Register

Developers Planet

Your answer is one click away!

smith February 2016

NativeCall Struct which contains Pointer

I have the following Struct :

typedef struct _info{
  DWORD myInfo;
  BYTE  *pInfo;
  LPWSTR ExtData;

} Info;

I represented this struct using NativeCall thus:

class Info is repr('CStruct') {
    has int32 $.myInfo;
    has Pointer[int8] $.pInfo ; 
    has Pointer[int16] $.ExtData;
}

Is this representation okay? How can I access and set the data which is pointed to by $.pInfo?

Answers


Marty February 2016

The representation seems ok to me... Given this invented C library: (please don't pick on my C foo - its beside the point)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef unsigned long int DWORD;
typedef unsigned char BYTE;
typedef char * LPWSTR;

typedef struct _info{
  DWORD   myInfo;
  BYTE   *pInfo;
  LPWSTR  ExtData;
} Info;


Info* create_info();
void  display_info();
void  double_info(Info*);

Info*
create_info() {
    DWORD init_myinfo    = 2016;
    BYTE  init_pinfo     = 37;
    char  init_ExtData[] = "Hello World";

    Info *new_info = malloc(sizeof(Info));
    if (new_info == NULL) {
        printf( "Memory alloc failed\n" );
        exit(1);
    }

    new_info->myInfo = init_myinfo;

    BYTE *pinfo = malloc(sizeof(BYTE));
    *pinfo = init_pinfo;
    new_info->pInfo = pinfo;

    char *ext_data = malloc(sizeof(init_ExtData));
    strcpy(ext_data, init_ExtData);
    new_info->ExtData = ext_data;

    return new_info;
}

void
display_info(Info *inf) {
    printf("myInfo: %lu\n", inf->myInfo);
    printf("pInfo:  %i\n", *inf->pInfo);
    printf("ExtData: %s\n", inf->ExtData);
}

void
double_info(Info *inf) {

    inf->myInfo *=  2;

    if ( *(inf->pInfo) < 128 )
        *(inf->pInfo) *= 2;

    int extdata_len = strlen(inf->ExtData);
    char *tmp_extdata = malloc(extdata_len * 2 + 2);
    strncpy(tmp_extdata, inf->ExtData, extdata_len);
    tmp_extdata[extdata_len] = '+';
    strcpy(&tmp_extdata[extdata_len+1], inf->ExtData);
    inf->ExtData = tmp_extdata;
}

then your perl6 struct definition using NativeCall more or less works:

#!/usr/bin/env perl6
use NativeCall;

class Info is repr('CStruct') {
    has int32          $.myInfo;
    has Pointer[int8]  $.pInfo ;
    has Pointer[Str]   $.ExtData;

    method Str {
      qq:to/END HERE/;
      myInfo: $!myInfo
      pInfo: { $!pInfo.deref }
      ExtData: { $!ExtData. 

Post Status

Asked in February 2016
Viewed 1,725 times
Voted 8
Answered 1 times

Search




Leave an answer


Quote of the day: live life