Call C/C++ Code from MATLAB Code

1 view (last 30 days)
Tareg Mohammed
Tareg Mohammed on 9 Nov 2021
Commented: Tareg Mohammed on 13 Nov 2021
I am trying to implement the following example:
Integrate External Code that Uses Custom Data Types
This example shows how to call a C function that uses data types that are not natively defined within MATLAB®.
consider the MATLAB function addCTypes.m:
function [out] = addCTypes(a,b)
%#codegen
% generate include statements for header files
coder.cinclude('MyStruct.h');
coder.cinclude('createStruct.h');
coder.cinclude('useStruct.h');
% initialize variables before use
in = coder.opaque('MyStruct');
out = 0;
% call C functions
in = coder.ceval('createStruct',a,b);
out = coder.ceval('useStruct',in);
end
The createStruct function outputs a C structure type:
#include <stdio.h>
#include <stdlib.h>
#include "MyStruct.h"
#include "createStruct.h"
struct MyStruct createStruct(double a, double b) {
struct MyStruct out;
out.p1 = a;
out.p2 = b;
return out;
}
The useStruct function performs an operation on the C type:
#include "MyStruct.h"
#include "useStruct.h"
double useStruct(struct MyStruct in) {
return in.p1 + in.p2;
}
To generate code, specify the source (.c) files as inputs:
codegen addCTypes -args {1,2} -report createStruct.c useStruct.c
and I get the follwong result:
------------------------------------------------------------------------
??? Build error: C compiler produced errors. See the Build Log for further details.
More information
Code generation failed: View Error Report
Error using codegen
Error in run (line 1)
codegen addCTypes -args {1,2} -report createStruct.c useStruct.c
should I make a file 'MyStruct.h', and how I should define it ?

Answers (1)

James Tursa
James Tursa on 12 Nov 2021
Edited: James Tursa on 12 Nov 2021
If your code includes a file called MyStruct.h, then yes you should have such a file. I would expect it to be something like this:
/* File: MyStruct.h */
struct MyStruct {
double p1;
double p2;
};
You need the other header files also. These files need to be in a directory that is visible to the compiler when it sees the #include lines.
  1 Comment
Tareg Mohammed
Tareg Mohammed on 13 Nov 2021
I included all relavent files in same directory, with MyStruct.h. and it still shows the following error.

Sign in to comment.

Categories

Find more on MATLAB Coder in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!