Filter löschen
Filter löschen

How to create a c++struct which is defined in extern c++ lib in MATLAB?

7 Ansichten (letzte 30 Tage)
I want to call a c++ method in matlab like:
loadlibrary('ASICamera2');
p = libpointer('string');
gpsData = struct();
x = calllib('ASICamera2','ASIGetDataAfterExpGPS', 0, p, 256*256, gpsData);
In 'ASICamera2.h',method 'ASIGetDataAfterExpGPS' is defined as follow. Obviously, the above matlab code dosen't work because p and gpsData are not correct data type.
int ASIGetDataAfterExpGPS(int iCameraID, unsigned char* pBuffer, long lBuffSize, ASI_GPS_DATA *gpsData);
typedef struct _ASI_GPS_DATA {
ASI_DATE_TIME Datetime;
double Latitude;
double Longitude;
char Unused[64];
} ASI_GPS_DATA;
typedef struct _ASI_DATE_TIME{
int Year;
char Unused[64];
} ASI_DATE_TIME;
Now I have two questions:
  1. How to create char* argument in matlab?
  2. How to create a struct likes ASI_GPS_DATA * in matlab?
I tried libstruct function in matlab but failed, if anyone can help me?

Akzeptierte Antwort

Harsh
Harsh am 30 Apr. 2024
Bearbeitet: Harsh am 30 Apr. 2024
Hi,
From what I can gather, you are trying to use a C/C++ function in MATLAB which uses a struct and are facing issues while using the structure.
Follow the following steps to initialize a C/C++ structure and char* in MATLAB:
(sample.c)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char* value;
} sampleStruct;
sampleStruct* initStruct(int id, char* value) {
sampleStruct* s = (sampleStruct*)malloc(sizeof(sampleStruct));
s->id = id;
s->value = strdup(value);
return s;
}
sampleStruct* useStruct(sampleStruct* s) {
return s;
}
Compile *.so file of sample.c
gcc -shared -fpic -o sample.so sample.c
Define a sample.h file
typedef struct {
int id;
char* value;
} sampleStruct;
sampleStruct* initStruct(int id, char* value);
sampleStruct* useStruct(sampleStruct* s);
Using the loadlibrary function, load sample.h
loadlibrary('sample.so', 'sample.h')
Call useStruct function which uses a structure from MATLAB using the calllib function in MATLAB.
s_ptr = calllib('sample', 'initStruct', 123, 'sampleStr');
val = calllib('sample', 'useStruct', s_ptr);
disp(val)
I hope this help, thanks!
  1 Kommentar
yijia
yijia am 30 Apr. 2024
Hi Harsh, thank you very much!
Your answer is very specific! Folloing step by step perfectly solves my questions.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Call C++ from MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by