Search code examples
c#cpinvokemarshalling

Marshal global variable in C#


I have 3 global variables in the C code: one int and two pointers to structures. I have to marshal them as public static members in the C# code, but i couldn't find any solution. I must mention that modifying the C code is the absolute last option.

I have to marshal this global:

extern const    msdk_FileSystemInterface*       m_fileInterface;

This is what i've tried so far, but doesn't compile:

    [DllImport("foo.so", EntryPoint = "m_fileInterface")]
    private static extern IntPtr _m_fileInterface { get; set; }
    public static msdk_FileSystemInterface m_fileInterface 
    { 
        get
        {
            return (msdk_FileSystemInterface)Marshal.PtrToStructure(_m_fileInterface, typeof(msdk_FileSystemInterface));
        }
    }

.

    [DllImport("foo.so", EntryPoint = "m_fileInterface")]
    private static extern IntPtr _m_fileInterface;
    public static msdk_FileSystemInterface m_fileInterface 
    { 
        get
        {
            return (msdk_FileSystemInterface)Marshal.PtrToStructure(_m_fileInterface, typeof(msdk_FileSystemInterface));
        }
    }

msdk_FileSystemInterface structure is available in the C# code (is already marshaled).

Does anyone have a solution for marsahalling globals or is impossible and I really have to them wrap them in a struct or add setters and getters into the C code?


Solution

  • You can use GetProcAddress to obtain the address of the exported globals. You cannot get the marshaller to do it with DllImport.

    So your two options are:

    1. Use GetProcAddress and do all the marshalling yourself.
    2. Add getters and setters to the C code and let the marshaller do the heavy lifting from there.

    Personally I would opt for option 2.