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

Val*_*itz 5 c matlab pointers shared-libraries loadlibrary

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

void myGetVersion( const char ** );
Run Code Online (Sandbox Code Playgroud)

C代码是:

const char *version=0;
myGetVersion( &version );
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你!

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

Amr*_*mro 8

答案是使用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
Run Code Online (Sandbox Code Playgroud)

version.c

#include "version.h"
#include <string.h>

DLL_IMPORT_EXPORT void myGetVersion(char **str)
{
    *str = strdup("1.0.0");
}
Run Code Online (Sandbox Code Playgroud)

您可以使用首选的编译器来构建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
Run Code Online (Sandbox Code Playgroud)

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

main.c中

#include <stdio.h>
#include <stdlib.h>
#include "version.h"

int main()
{
    char *str = NULL;
    myGetVersion(&str);
    printf("%s\n", str);
    free(str);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在一切正常,这里是如何使用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
Run Code Online (Sandbox Code Playgroud)

返回的字符串输出:

Functions in library libversion:
stringPtrPtr myGetVersion(stringPtrPtr)

       Value: {''}
    DataType: 'stringPtrPtr'

dllVersion =
1.0.0
Run Code Online (Sandbox Code Playgroud)