MATLAB: How to access an exported variable in a DLL

MATLAB: How to access an exported variable in a DLL

dllexportedMATLABmembervariable

I have complied DLL that I am able to use in a C++, and I would like to use it in MATLAB.
The C++ code utilizes GetProcAddress to access a structure that is exported by the library:
structPointer = (ext_struct*)GetProcAddress(myDLL, "exportedStructure");
Which we must later write some data to:
fscanf(input_data, "%d", &structPointer->a);
In MATLAB I am able to successfully load the library and can see the functions in the library using
loadlibrary(myDLL)
libfunctions(myDLL)
I would like an equivalent to the GetProcAddress which would allow me to access the member variable.

Best Answer

  • You can use the ‘calllib’ function to access exported variables in a shared library.

    For example, if I have the following structure and exported variable in my library header file:

    struct c_struct {
        double a;
        int b;
    };
    EXPORTED_FUNCTION struct c_struct exportedStruct;
    

    And the c_struct variable ‘exportedStruct’ is defined in my library as:

    struct c_struct exportedStruct = {1, 2};
    

    Then I can access this structure from MATLAB as follows:

    >> loadlibrary('myLibrary')
    >> lp = calllib('myLibrary', 'exportedStruct')
    >> lp.Value
    ans = 
      struct with fields:
    
          a: 1
          b: 2

    This will return a ‘lib.pointer’ object pointing to the variable, which you can then use to interact with the variable:

    >> lp.Value
    ans =    
        struct with fields:     
            a: 1
            b: 2
    >> lp.Value.p1 = 2;
    
  • Add a Comment

    Your email address will not be published. Required fields are marked *