matlab - 无法在 native x32 共享库和 matlab 之间编码(marshal) char**

标签 matlab shared-libraries marshalling native loadlibrary

我尝试使用 loadlibrarycalllib 从 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被编码为int32formatcstringinfostringPtrPtr。这是默认情况下 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/

相关文章:

Matlab如何轻松循环圆形数组

matlab - 带汉宁窗的傅立叶滤波器后恢复信号

matlab - 按顺时针顺序检测非凸多边形的角坐标 MATLAB

algorithm - 计算深度图像中像素与相机平面的角度

linux - 如何从 Linux .so 文件中删除未使用的代码?

使用 GNU 工具链 (gcc/ld) 从静态库创建共享库

android - 如何在 Ubuntu 中使用 Android 共享库

c# - DllImport 中的编码(marshal)处理、StringBuilder 和字符指针

java - JAXB 将多个对象编码到一个文件

XML 编码 : mix attributes and elements