我尝试使用 loadlibrary
和 calllib
从 matlab 调用 native 共享库中的函数,但无法获取从内部分配的字符串库作为 char**。
这是 native 库的(简化)代码:
#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
为cstring
和 info
为 stringPtrPtr
。这是默认情况下 perl 的脚本从“MyDll.h”创建的内容,也是此 thread 中建议的内容。 .
我尝试了许多其他编码(marshal)类型,但无法弄清楚如何获取 info
的正确值。
注意:这里没有报告,但 native 库还定义了一个函数来释放为 info
参数分配的内存。我的Matlab版本是7.2.0.232
最佳答案
上次我tried this ,我发现指针类型的输入参数没有就地修改,而是返回了附加输出参数,其中包含任何更改的指针类型输入的副本。
您可以通过以下方式查看这一事实:
>> libfunctions MyDll -full
Functions in library MyDll:
[int32, cstring, stringPtrPtr] MyFunction2(int32, cstring, stringPtrPtr)
奇怪的是,当我在最新的 R2013a 上再次尝试时,输入参数确实被修改了。从那时起,某些事情一定发生了变化:)
因此,就您的情况而言,您应该调用:
info = libpointer('stringPtrPtr',{''});
[val,~,info2] = calllib('MyDll', 'MyFunction2', 666, 'kikou', info)
并检查输出info2
关于matlab - 无法在 native x32 共享库和 matlab 之间编码(marshal) char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240474/