Search code examples
c#pinvokedllimport

C DLL function got char* parameter and I want to import in C# project


I have a DLL wrote in C and I want to export the function :

__declspec( dllexport ) int GetDllVersion(char *Version);

and I have

class DllSolderMask
{
     [DllImport("Dll.dll", CharSet=CharSet.Ansi)]
     public static extern int GetDllVersion(ref string version);
}

static void Main(string[] args)
{
        string strVersion;

        DllSolderMask.AltixDllVersion(ref strVersion);

        Console.WriteLine(strVersion.ToString());
}

The char *Version is obviously a character's array and so ref string strVersion could do the job but it doesn't work.


Solution

  • Ok I found out how to properly use StringBuilder :

    [DllImport("AltixDll.dll", CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
    public extern static int AltixDllVersion([MarshalAs(UnmanagedType.LPStr)] StringBuilder DllVersion);
    
    StringBuilder str = new StringBuilder();
    DllSolderMask.AltixDllVersion(str);
    lblDll.Text = str.ToString();
    

    the byte array way is not dynamic and it requires me to know the space I need in my array declaration, and it's not accurate.