传递指针参数在MATLAB到C-DLL函数foo(CHAR **) [英] Passing pointer argument in MATLAB to a C-DLL function foo(char**)
问题描述
我写一个C-DLL是从MATLAB调用。
它是可调用为const char **
参数的函数?例如。
I am writing a C-DLL to be called from MATLAB.
Is it possible to call a function with const char **
parameter? e.g.
void myGetVersion( const char ** );
的C code将是:
The C code would be:
const char *version=0;
myGetVersion( &version );
什么会相应MATLAB- code(如果可能的话)?
What would be corresponding MATLAB-Code (if it is possible at all)?
非常感谢你!
P.S .:
我觉得这是帮助页面,但我不能发现我的情况: - (
P.S.: I think this is the help page, but I couldn't find my case :-(
推荐答案
答案是使用的 LIBPOINTER 功能<一个href=\"http://stackoverflow.com/questions/7445054/passing-pointer-argument-in-matlab-to-a-c-dll-function-foochar/7445529#7445529\">@JonasHeidelberg建议。让我展开他的工作的例子..解
The answer is to build a pointer to a c-string using the LIBPOINTER function as @JonasHeidelberg suggested. Let me expand his solution with a working example..
首先让我们建立一个简单的DLL:
First lets build a simple DLL:
#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 <string.h>
DLL_IMPORT_EXPORT void myGetVersion(char **str)
{
*str = strdup("1.0.0");
}
您可以使用preferred编译器来构建DLL库(Visual Studio中,MinGW的GCC ..)。我使用MinGW的编译上面的,下面是我使用生成文件:
You can use your preferred compiler to build the DLL library (Visual Studio, MinGW GCC, ..). I am using MinGW to compile the above, here is the makefile I am using:
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程序测试库:
Before we move to MATLAB, lets test the library with a C program:
#include <stdio.h>
#include <stdlib.h>
#include "version.h"
int main()
{
char *str = NULL;
myGetVersion(&str);
printf("%s\n", str);
free(str);
return 0;
}
现在,所有的工作,这里是如何使用该库从MATLAB:
Now that all is working, here is how to use this library from MATLAB:
%# 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
以字符串返回的输出:
The output with the string returned:
Functions in library libversion:
stringPtrPtr myGetVersion(stringPtrPtr)
Value: {''}
DataType: 'stringPtrPtr'
dllVersion =
1.0.0
这篇关于传递指针参数在MATLAB到C-DLL函数foo(CHAR **)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!