Question

i have some code in C++ (www.NR.com functions), which i would like to use in SQL Server 2008R2 CLR SP. Tried to make a wrapper in C#, but no luck. Perhaps somebody has a working sample or manual how to make such wrapper and set all required compiler/linker options?

Thanks

Was it helpful?

Solution

MSDN has all the info to marshall the parameters from native code to managed .NET

http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx

http://msdn.microsoft.com/en-us/library/z6cfh6e6(v=vs.71).aspx

This article explains how to consume unmanaged code (C++ classes)

http://www.codeguru.com/cpp/cpp/cpp_managed/interop/article.php/c6867/Consuming-Unmanaged-C-Class-Libraries-from-NET-Clients.htm

There's a catch with 64-bit native code (not mentioned in this article because it was before the actual widespread of amd64). The linker parameters have to be tweaked and I did this only by trial and error.

On the second thought, the thing with NR.com is even simpler. You can just create a .DLL with all the functions you need. This is called P/Invoke and it is way simpler than C++/CLI solution I mentioned above.

Basically, for the C code like

extern "C" void do_something_with_numbers(double* array, int len);

you create the Wrapper.DLL with this function exported.

Then in C# you just declare

class MyNRWrapper
{
     [DllImport("WrapperDLL.dll", EntryPoint="do_something_with_numbers")]
     public static extern void DoSomething([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] double [] array, int size );
};

The problems you are experiencing might have come from the fact that in DLL you forgot to declare the functions as extern "C" and they become mangled by the C++ compiler. Use the CFF Explorer tool and take a look in the Export section of the Wrapper.DLL to see if it actually has the function you are exporting. If the name is mangled either add the extern "C" modifier or change the EntryPoint name in C#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top