Calling D DLL from C# and passing/retrieving string variables

Andre andre at s-e-a-p.de
Wed Oct 12 09:00:10 PDT 2011


Hi,
I try to write a DLL in D which could be called from C#. For testing I want
to write a Concatenate method. The call to the DLL method does not raise
any exception in C# but the out string strResult is empty or it contains
invalid characters.

I tested it with strcopy, toStringz, string.ptr and toUTFz or just passing
a pointer.
Could you give some advice?

D Dll
module mydll;
import std.c.stdio;
import std.c.windows.windows;
import std.c.string;

export extern(C) bool concatenate(
	LPCTSTR str1, LPCTSTR str2, LPTSTR strResult)
{
   strcpy(strResult, "Test");
   return false;
}

C#
namespace DllClient
{
    class Program
    {
        [DllImport("mydll.dll",
            CallingConvention = CallingConvention.Cdecl,
            SetLastError = false, CharSet = CharSet.Auto)]
            private static extern bool concatenate(
                string str1, // in
                string str2, // in
                StringBuilder strResult); // out

        static void Main(string[] args)
        {
            StringBuilder sBuffer = new StringBuilder(4);
            concatenate("abc", "def", sBuffer);
            System.Console.WriteLine("Concatenate Result: " +
sBuffer.ToString());
            System.Console.ReadLine();
        } 
    }
}

Kind regards
André


More information about the Digitalmars-d-learn mailing list