将MATLAB中的指针参数传递给C-DLL函数foo(char **)

我正在编写一个从MATLAB调用的C-DLL。 是否可以使用const char **参数调用函数? 例如

 void myGetVersion( const char ** ); 

C代码将是:

 const char *version=0; myGetVersion( &version ); 

什么是相应的MATLAB-Code(如果可能的话)?

非常感谢你!

PS:我认为这是帮助页面 ,但我找不到我的情况:-(

答案是使用LIBPOINTER函数构建一个指向c-string的指针,如@JonasHeidelberg所建议的那样。 让我用一个工作实例扩展他的解决方案..

首先让我们构建一个简单的DLL:

version.h中

 #ifndef VERSION_H #define VERSION_H #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 # ifdef BUILDING_DLL # define DLL_IMPORT_EXPORT __declspec(dllexport) # else # define DLL_IMPORT_EXPORT __declspec(dllimport) # endif #else # define DLL_IMPORT_EXPORT #endif DLL_IMPORT_EXPORT void myGetVersion(char**str); #ifdef __cplusplus } #endif #endif 

version.c

 #include "version.h" #include  DLL_IMPORT_EXPORT void myGetVersion(char **str) { *str = strdup("1.0.0"); } 

您可以使用首选的编译器来构建DLL库(Visual Studio,MinGW GCC,..)。 我正在使用MinGW编译上面的代码,这里是我正在使用的makefile:

Makefile文件

 CC = gcc all: main libversion.dll: version.c $(CC) -DBUILDING_DLL version.c -I. -shared -o libversion.dll main: libversion.dll main.c $(CC) main.c -o main -L. -lversion clean: rm -rf *.o *.dll *.exe 

在我们转向MATLAB之前,让我们用C程序测试库:

main.c中

 #include  #include  #include "version.h" int main() { char *str = NULL; myGetVersion(&str); printf("%s\n", str); free(str); return 0; } 

现在一切正常,这里是如何使用MATLAB中的这个库:

testDLL.m

 %# load DLL and check exported functions loadlibrary libversion.dll version.h assert( libisloaded('libversion') ) libfunctions libversion -full %# pass c-string by reference pstr = libpointer('stringPtrPtr',{''}); %# we use a cellarray of strings get(pstr) calllib('libversion','myGetVersion',pstr) dllVersion = pstr.Value{1} %# unload DLL unloadlibrary libversion 

返回的字符串输出:

 Functions in library libversion: stringPtrPtr myGetVersion(stringPtrPtr) Value: {''} DataType: 'stringPtrPtr' dllVersion = 1.0.0 

看看使用指针 ,在MATLAB文档中传递一个字符串数组 (从您在问题中链接的帮助页面链接),似乎您需要在MATLAB中构建一个libpointer对象 ,类似于

 version = libpointer('stringPtrPtr',{''}); %# corrected according to Amro's comment calllib('yourCdll', 'myGetVersion', version) 

(我现在没有DLL来测试这个,我对C指针不是很坚定,所以不能保证……希望这是朝着正确方向迈出的一步)

我无法获得@ Amro的解决方案(旧版本的MATLAB?)。 所以,我必须做一些更有创意的事情:

 pstr = libpointer('voidPtr'); ret = calllib('libversion', 'myGetVersion', pstr); % establish the length n = 0; while n==0 || pstr.Value(n) ~= 0 n=n+1; pstr.setdatatype('uint8Ptr', 1, n); end % truncate to exclude the NULL character pstr.setdatatype('uint8Ptr', 1, n-1); % convert to string display(char(pstr.Value))