SQL Server 2005 CLR integration problems with unmanaged code

Hi,

With SQL Server 2005 I'm trying to define a CLR integration UDF that calls unmanaged C++ code contained in a .dll.

I have the following two signed assemblies:

1) 'wrapper' - this assembly is basically a wrapper class writen in C++ managed extensions code that calls a legacy library written in unmanaged C++

2) 'provider'- this assembly offers services some of which are contained in the 'wrapper' assembly. This class is written in C# and its assembly is marked as unsafe since it is calling unmanaged code

The problem is that when I run the assembly creation statement:

CREATE ASSEMBLY [Provider]
FROM 'c:\Development\Provider.dll'
WITH PERMISSION_SET = UNSAFE;

Produces the error:

Msg 6544, Level 16, State 1, Line 1
CREATE ASSEMBLY for assembly 'Provider' failed because assembly 'wrapper' is malformed or not a pure .NET assembly.
Unverifiable PE Header/native stub.

I understand the nature of the error; wrapper.dll is unsafe unmanaged code and the documentation of CLR integration security states:

"executing from within an UNSAFE assembly can call unmanaged code"

I would think that the 'PERMISSION_SET = UNSAFE' would take care of this situation.

BTW, I can sucessfully call, from a console C# program, the services contained in wrapper.dll, the problem is that I can't get it to work within SQL Server 2005.

Can someone help me out on this


Answer this question

SQL Server 2005 CLR integration problems with unmanaged code

  • Lou_b

    Yes, you can call unmanaged code from SQLCLR assemblies, but you can not catalogue an assembly in SQL Server which contains unmanaged code. In your managed asembly in SQL you can either do COM interop calls, or P/Invoke calls. From what you have written above, I'd assume you would need to call P/Invoke into your legacy C++ dll.

    Niels


  • Guru2228

    Using p/invoke is the key!

    I just export the functions in my wrapper class as one would do with any normal DLL.

    Then in the CLR calling class one would define the imported functions using DllImport:

    [DllImport("wrapper.dll")]

    public static extern int Initialize(int source, String arg);

    Then just call it within the class and it works! One just has to pay attention to any unusual marshalling that one might need, for example one parameter was defined as:

    char OutData[]

    so in the DllImport it was defined as:

    [MarshalAs(UnmanagedType.LPArray)] byte[] OutData

    and the MarshalAs takes care of this type of parameter.

    Thanks for your help Niels.


  • SQL Server 2005 CLR integration problems with unmanaged code