C# – Passing string as PChar from CSharp to Delphi DLL

cdelphidllimport

I'm trying to pass a string from C# to Delphi built DLL.
Delphi DLL expects PChar.

Here is Delphi export

procedure DLL_Message(Location:PChar;AIntValue :integer);stdcall;
external 'DLLTest.dll';

C# import(last one I tried, there were string, char* ref string …)

[DllImport(
            "DLLTest.dll", 
            CallingConvention = CallingConvention.StdCall,
            CharSet = CharSet.Ansi,
            EntryPoint = "DLL_Message"
        )]
        public static extern void DLL_Message(IntPtr Location, int AIntValue);

I get access violation accessing value in any way.

Is there any solution to pass a string value as PChar in C#?

Best Answer

Try with the MarshalAs attribute that allows you to control the native type that is used.

A list of types can be found in MSDN:

http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.unmanagedtype.aspx

DllImport(
            "DLLTest.dll", 
            CallingConvention = CallingConvention.StdCall,
            CharSet = CharSet.Ansi,
            EntryPoint = "DLL_Message"
        )]
        public static extern void DLL_Message(
            [MarshalAs(UnmanagedType.LPStr)] string Location,
            int AIntValue
        );
Related Topic