CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2011
    Posts
    1

    C# MarshalException C code

    Hi all!.

    I would like use unmanaged code from C in C#.

    I built a DLL with C code with this functions:

    struct GetPluginData
    {
    int data[22];
    };

    DLLEXPORT extern "C" __declspec (dllexport) GetPluginData GetDataArray(int number);

    In C# I've got this code:
    [StructLayoutAttribute(LayoutKind.Sequential, Pack=1)]
    public unsafe struct GetPluginData
    {
    /// int[22]
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 22, ArraySubType = UnmanagedType.I4)]
    public int[] data;
    }

    [DllImport("RBRPlugin.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetDataArray")]
    [return: MarshalAs(UnmanagedType.Struct)]
    public static extern GetPluginData GetDataArray(int number);

    In button event or othe place code, I wrote this:
    GetPluginData tes = GetDataArray(1);

    And I'm getting the error: The type signature of this method is not PInvoke compatible.

    I'm looking for information throught google, but no result found...

    Thanks in advance!

  2. #2
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: C# MarshalException C code

    You can't return structs from PInvoke methods.

    You'll have to do it like this :

    Code:
    // C++
    struct GetPluginData
    {
    int data[22];
    };
    
    DLLEXPORT extern "C" __declspec (dllexport) void GetDataArray(int number, GetPluginData *pData);
    And in c#

    Code:
    [StructLayoutAttribute(LayoutKind.Sequential, Pack=1)]
    public unsafe struct GetPluginData
    {
         [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 22,  ArraySubType = UnmanagedType.I4)]
         public int[] data;
    }
    
    [DllImport("RBRPlugin.dll", CallingConvention = CallingConvention.CDecl, EntryPoint = "GetDataArray")]
    public static extern void GetDataArray(int number, ref GetPluginData val);
    Also note the calling convention is CDecl by default for __declspec(dllexport). The extern "C" means the method name exported by the dll isn't decorated.

    Darwen.
    Last edited by darwen; December 23rd, 2011 at 06:17 AM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured