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

casual.james at yahoo.es casual.james at yahoo.es
Wed Oct 12 12:49:14 PDT 2011


On Wed, 12 Oct 2011 18:00:10 +0200, Andre <andre at s-e-a-p.de> wrote:

> 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é

-            SetLastError = false, CharSet = CharSet.Auto)]
+            SetLastError = false, CharSet = CharSet.Ansi)]

CharSet.Auto will choose UTF-16 unless you add use the Windows ANSI method  
convention (i.e. name your function "concatenateA"). In D, LPTSTR will use  
ANSI by default.


More information about the Digitalmars-d-learn mailing list