Wednesday, June 20, 2007

Marshalling Problem Practically applied

8:22 PM 6/20/2007

Simple DLL Developement :

1. open the simple Win32 DLL project ( TestDll) , it will creates the stdafx.h, stdafx.cpp and TestDll.cpp
2.Add the new header file (TestDll.h)

within the TestDll.h file I added the following code >..

#ifdef DLLDIR_EX
#define DLLDIR __declspec(dllexport) // export DLL information
#else
#define DLLDIR __declspec(dllimport) // import DLL information
#endif

extern "C"
{
bool DLLDIR GetStatusKeyword();
BOOL DLLDIR GetStatusTypedef();
}

within the TestDll.cpp file, I added the following :

#include "TestDll.h"

bool DLLDIR GetStatusKeyword()
{
return false;
}

BOOL DLLDIR GetStatusTypedef()
{
return false;
}



Select menu items as follows ...

Project ->Settings ->C++ -> General option

Add the DLLDIR_EX macro in the "Preprocessor Definitions " text box.

and then compile it

they will show the EXPORTS keyword in a text box and compile the DLL project.

I got the TestDll.dll and TestDll.lib output files .




Develope the C# client application :

Create the C# Console application and add the namespace "System.Runtime.InteropServices" to it
and add the code as follows :


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

namespace TestDLLClient
{
class Win32API
{
[DllImport("TestDLL.dll")]
public static extern bool GetStatusTypedef();

[DllImport("TestDLL.dll")]
public static extern bool GetStatusKeyword();
}

class Program
{
static void Main(string[] args)
{
if (Win32API.GetStatusKeyword())
{
Console.WriteLine("\n GetStatusKeyword() fn succeeded ");
}
else
{
Console.WriteLine("\n GetStatusKeyword() fn failed ");
}

if (Win32API.GetStatusTypedef())
{
Console.WriteLine("\n GetStatusTypedef() fn Succeeded");
}
else
{
Console.WriteLine("\n GetStatusTypedef() fn failed");
}

Console.Read();
}
}
}


Next Copy the Testdll.dll and Testdll.lib to the "debug" folder of the C# client application.
then compile and run the C# application.

we got the output of the C# application is as follows:


GetStatusKeyword() fn succeeded

GetStatusTypedef() fn failed



Guys the problem is not over,

Next I modified the dll code as follows :


bool DLLDIR GetStatusKeyword()
{

OutputDebugString(" \n GetStatusKeyword() fn ..."); // This will writes the string in debug view...
return false;
}

BOOL DLLDIR GetStatusTypedef()
{
return false;
}



Next Compile the DLL project and copy the TestDll.dll and TestDll.lib to the C# client application's "Debug" folder.


Now Compile the C# application and see the result, u may wonder about the things...

The output is as follows :


GetStatusKeyword() fn failed
GetStatusTypedef() fn failed


It is a funny thing...


Note :
TestDLL application is developed in Visual studio 6.
C# client application is developed in .NET 2005...

Any guys got this problem before or try these things ....

No comments: