我正在尝试使用 matlab 调用本机共享库中的函数loadlibrary
,calllib
但我无法获取从库内部分配为 char** 的字符串。
这是本机库的(简化)代码:
#include <malloc.h>
#include <string.h>
#define DllExport __declspec(dllexport)
DllExport __int32 __stdcall MyFunction1()
{
return 42;
}
DllExport __int32 __stdcall MyFunction2(__int32 handle, const char* format, char** info)
{
*info = _strdup(format);
return handle;
}
这是来自matlab端的(测试)代码:
function [] = test()
%[
loadlibrary('MyDll', @prototypes);
try
% Testing function 1
val1 = calllib('MyDll', 'MyFunction1');
disp(val1); % ==> ok the display value is 42
% Testing function 2
info = libpointer('stringPtrPtr', {''});
val2 = calllib('MyDll', 'MyFunction2', 666, 'kikou', info);
disp(val2); % ==> ok the value is 666
disp(info.Value{1}); % ==> ko!! The value is still '' instead of 'kikou'
catch
end
unloadlibrary('MyDll');
%]
%% --- Define prototypes for 'MyDll'
function [methodinfo, structs, enuminfo] = prototypes()
%[
% Init
ival = {cell(1,0)};
fcns = struct('name',ival,'calltype',ival,'LHS',ival,'RHS',ival,'alias',ival);
structs = []; enuminfo = []; fcnNum = 0;
% Declaration for '__int32 __stdcall MyFunction1()'
fcnNum = fcnNum+1; fcns.name{fcnNum} = 'MyFunction1'; fcns.calltype{fcnNum} = 'stdcall'; fcns.LHS{fcnNum} = 'int32'; fcns.RHS{fcnNum} = {};
% Declaration for '__int32 __stdcall MyFunction2(__int32 handle, const char* format, char** info)'
fcnNum = fcnNum+1; fcns.name{fcnNum} = 'MyFunction2'; fcns.calltype{fcnNum} = 'stdcall'; fcns.LHS{fcnNum} = 'int32'; fcns.RHS{fcnNum} = { 'int32', 'cstring', 'stringPtrPtr'};
methodinfo = fcns;
%]
从prototypes
子函数中可以看出,handle
被编组为int32
、format
ascstring
和info
as stringPtrPtr
。这是默认情况下 perl 的脚本从“MyDll.h”创建的,也是这个线程中建议的。
我尝试了许多其他封送处理类型,但无法弄清楚如何为info
.
注意:这里没有报告,但是本机库还定义了一个函数来释放为info
参数分配的内存。我的 Matlab 版本是 7.2.0.232