Monday, January 2, 2012

How to call a custom C# dll in VUGen

It’s not possible to directly call a C#.Net code in LR; for that you need to create a wrapper dll around the original dll. Below is a sample example and ways to do it:


If your core code implementation looks like below:
*********************************************************************
using System;
namespace intmath
{
public class Class1
{
public Class1()
{
}


public static int sum(int a, int b)
{
return (a+b);
}

}

}


*********************************************************************
And this code creates a dll called as “intmath.dll” which is in c# code.

1.Launch Visual Studio .NET and create a new C++ Win32 Project. In the application settings, set the application type to "Dll."
2. Set all required configuration properties required for using managed extensions in the project properties.
a.Go to Configuration Properties -> General.
b.Set the "Use Managed Extensions" option to Yes.
c.Go to the properties of the .cpp file, and under Configuration Properties -> C/C++ -> Pre-Compiled headers, set the "Create/Use Precompiled Header" option to "Not Using Precompiled Headers."

3. Add a reference to the managed code library in this project. //In this case it will be “intmath.dll”


4. In the projects .cpp file, add methods to make calls to the managed code. Add code in the beginning to include the appropriate namespaces.


Below is a code snippet of the cpp file


*************************************************************************
#using

using namespace System;
using namespace intmath; // This is the namespace which is of your original file

#include "stdafx.h"


BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
extern int Calladd(int, int);


extern "C"
{
__declspec(dllexport) int add(int a, int b)
{
return Calladd(a,b);
}


}


int Calladd(int a, int b){
return Class1::sum(a,b); // call to the original function written in C#
}


***************************************************************************
build this project and generate your dll, in this case it will be known as “mytest.dll” (name of your project)

Then I can use this dll in my VUGen script like shown below:
****************************************************************************


Action()
{

lr_load_dll("mytest.dll"); // Instead of loading the original “intmath.dll”
lr_output_message("add(12, 13) = %d", add(12, 13));
return 0;


}

*******************************************************************************

Hope this will help you in resolving issue with dll loading.


1 comment:

  1. Thanks Sunil, It was a nice tutorial. I tried to follow user steps to create "mytest.dll" but end-up with error. Could you please repost it with screenshots that would be great.

    ReplyDelete