2

我正在尝试使用 matlab 调用本机共享库中的函数loadlibrarycalllib但我无法获取从库内部分配为 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被编组为int32formatascstringinfoas stringPtrPtr。这是默认情况下 perl 的脚本从“MyDll.h”创建的,也是这个线程中建议的。

我尝试了许多其他封送处理类型,但无法弄清楚如何为info.

注意:这里没有报告,但是本机库还定义了一个函数来释放为info参数分配的内存。我的 Matlab 版本是 7.2.0.232

4

1 回答 1

2

上次我尝试这个时,我发现指针类型的输入参数没有就地修改,而是返回了额外的输出参数,其中包含任何指针类型输入的副本以及任何更改。

您可以通过以下方式看到这个事实:

>> 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

于 2013-04-26T16:35:05.227 回答