フィルターのクリア

Pass opaque structs to Shared C Library Functions

7 ビュー (過去 30 日間)
Martin März
Martin März 2022 年 1 月 26 日
回答済み: BhaTTa 2023 年 11 月 8 日
I am using a shared library with calllib and an opaque type as function argument (handle).
The calllib function throws the error:
"A field does not match one in the struct."
But am not able to define this struct more precise because it is not visible for me (opaque).
My Code is:
factory.h
typedef struct _HFactory* HFactory; ///< opaque type
...
API_DLL status_t factory_getHandle(HFactory* const hFactory);
...
API_DLL status_t factory_getInfos( HFactory hFactory);
...
getinfo.m
...
p = libpointer('s_HFactoryPtrPtr');
[ status ] = calllib('lib_factory','factory_getHandle', p);
[ status ] = calllib('lib_factory','factory_getInfos', get(p)); %error
Is there another way to use opaque-structs as handler?

回答 (1 件)

BhaTTa
BhaTTa 2023 年 11 月 8 日
When working with opaque struct types as function arguments in MATLAB, you can encounter issues when using calllib due to the lack of visibility into the internal structure of the opaque type. One approach to circumvent this issue is to use a MEX function to interface with the shared library. Here's how you can do it:
  1. Create a MEX Function: Write a C/C++ MEX function that wraps the functionality of the shared library and exposes it to MATLAB. This allows you to have more control over the opaque struct type.
  2. Pass the Opaque Type as a Pointer: Modify the MEX function to accept a pointer to the opaque struct type as an input argument. You can use the mxGetScalar or mxGetData functions to retrieve the pointer from the MATLAB input.
  3. Call the Shared Library Functions: Within the MEX function, you can call the shared library functions using the opaque struct pointer obtained from MATLAB. This way, you have direct access to the opaque struct and can pass it to the library functions without relying on calllib.
  4. Build and Use the MEX Function: Compile the MEX function using the MATLAB MEX compiler. Once built, you can call the MEX function from MATLAB just like any other MATLAB function, providing the necessary input arguments.
By using a MEX function, you have more control over the opaque struct type and can directly pass it to the shared library functions. This approach allows you to bypass the limitations of calllib when working with opaque types.
Note: Make sure to carefully handle memory management when working with pointers and opaque types in the MEX function to avoid memory leaks or access violations.

カテゴリ

Help Center および File ExchangeCall C from MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by