Praveen Katiyar' Blog

Learning along the way . . . .

Interoperability Returning a string from Wn32 DLL

Define  a function in native dll (let say it “Win32Native.dll”)  as shown below.

extern "C" __declspec(dllexport)  char * GetStringFromDLL()
{
    const size_t alloc_size = 128;
    STRSAFE_LPSTR result=(STRSAFE_LPSTR)
CoTaskMemAlloc(alloc_size);
    STRSAFE_LPCSTR teststr = "This is return string From Native DLL";
    StringCchCopyA ( result, alloc_size, teststr );
    return result;
}

Point of Interest

  • STRSAFE_LPSTR is a typedef of char *
  • StringCchCopy is a replacement for strcpy (with safety).  The size, in characters, of the destination buffer is provided to the function to ensure that StringCchCopyb does not write past the end of this buffer. has two variants.

Writing the client code (the managed part)

one can simple create a console base application which can use this dll. let’s name it MarshallingTest.

see the code snippet below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace MarshallingTest
{
    class Program
    {
       [DllImport("Win32Native.dll")]
public static extern String GetStringFromDLL();

        static void Main(string[] args)
        {
            Console.WriteLine("Line displayed below is returned from a Native DLL");
            string strData = GetStringFromDLL();
            Console.WriteLine ( "Returned value [" + strData +"]" );
        }
    }
}

Point of Interest

  • namespace System.Runtime.InteropServices;  defines the declarations necessary for Interop operations, like DllImport,
  • DllImport defines the DLL entry point.

compile and execute you will get following output.

image

 

Advertisements

July 30, 2013 - Posted by | CodeProject, Interoperability, Win32 | , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: