Click here to Skip to main content
Click here to Skip to main content

How to Automate Exporting .NET Function to Unmanaged Programs

, 21 Nov 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Post-build tool which can automate exporting .NET function to unmanaged programs

Introduction

Exporting functions to unmanaged programs - why not? I don't want to change *.il files by hand. I need to automate this. So here we go...

Background

A few days ago, I was writing a program (Terminal Services addin). The first problem was that I couldn't write this in C# ... Ok. I started writing it in C++/CLI. But there was another problem - mstsc.exe doesn't like to load such a library. Ok. No problem. I started another project (in C++/CLI - the first I change to pure C++) which exports one function. The first library loaded the second one and everything worked. But for dependencies, I needed easy deployment without installing VC80 runtimes... So I tried to find a way to export the function from C#. And I found it. While I was working with a project, I compiled it often and changing *.il files by hand was really annoying. That's why I made this tool. (Anyway later I found that the first library can be written in C# but it is a topic for another article - "How to write Terminal Services addin in pure C#" .)

Using the Code

Well the code is just the code ... it's a home-grown parser with some other functionality... So I'll rather write how to use it (and sometimes how it works).

Beginning

What you need to use it:

  • Framework 2.0 SDK
  • Visual Studio 2005 (optional)

First you should download the code (there are two projects ExportDll.exe and ExportDllAttribute.dll) and build it.

Then you should know how to use it... After creating the library project in C# or VB.NET, you need to add dependency to ExportDllAttribute. "Oh no, not another dependency" - you'll say. Easy ... just wait ... This library contains an attribute which tells ExportDll.exe that some function needs to be exported.

How It Works

As I said, ExportDll.exe needs to know which functions need to be exported. So you'll write something like this:

public class SomeClassName
{
    //second parameter of attribute is calling convention,
    //default is StdCall but u can use others fx.:
    [ExportDllAttribute.ExportDll("ExportNameOfFunction",
    System.Runtime.InteropServices.CallingConvention.Cdecl)]
    public static void SomeFunctionName()
    {
        System.Console.WriteLine("I really do nothing");
    }
}

After compiling, you need to use ExportDll tool to export this:

ExportDll.exe full_path_to_yours_dll\yoursdll.dll [/Release|/Debug]

Note: /Release flag is default. What exactly does ExportDll do:

  • Reads DLL as assembly and makes a dictionary of exported function
  • Decompiles DLL
  • Searches and replaces some stuff in IL code (If you want to know what, read the article that I mentioned in the "Background" section.)
  • Deletes ExportDllAttribute dependency

    .assembly extern ExportDllAttribute
    {
      .ver x:x:x:x
    }

    and

    .custom instance void
        [ExportDllAttribute]ExportDllAttribute.ExportDllAttribute ...
  • Compiles modified IL code again

Post-building in Visual Studio 2005

How? It's easy... Just add in Project property named "Post-build event command".

"path_to_tools\ExportDll.exe" "$(TargetPath)" /$(ConfigurationName)

OMG! It's Not Working

Hmm... Yes, forgot to mention about ExportDll.exe.cofig ...

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" 
        type="System.Configuration.ApplicationSettingsGroup, 
        System, Version=2.0.0.0, Culture=neutral, 
        PublicKeyToken=b77a5c561934e089" >
            <section name="ExportDll.Properties.Settings"
        type="System.Configuration.ClientSettingsSection,
        System, Version=2.0.0.0, Culture=neutral,
        PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <ExportDll.Properties.Settings>
            <setting name="ildasmpath" serializeAs="String">
                <value>C:\Program Files\
                Microsoft Visual Studio 8\SDK\v2.0\Bin\ildasm.exe</value>
            </setting>
            <setting name="ilasmpath" serializeAs="String">
                <value>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ilasm.exe
                </value>
            </setting>
        </ExportDll.Properties.Settings>
    </applicationSettings>
</configuration>

You need to configure path to ilasm and ildasm.

Updates

New version

  • now accept MarshalAsAtrribute
  • new commands in command line support: first had to be TargetPath then you can add:
    /release or /debug - /release id default
    /AnyCPU or /x64 - /AnyCPU is default its for 32/64 bit (for itanium add /PE64 /ITANIUM)
    ... any valid command for ildasm.exe
  • support fo x64
    "path_to_tools\ExportDll.exe" "$(TargetPath)" /$(ConfigurationName) /$(PlatformName)
    if PlatformName == "AnyCPU" then compiles for 32 bit
    if PlatformName == "x64" then compiles for 64 bit
  • now its compiled for runtime 4.0(ExportDll.exe) and 2.0 (ExportDllAttribut.dll) so it should be working for frameworks 2.0 - 4.0
  • it can compile for 2.0 or 4.0 runtime (runtime its not framework - frm 3.0 and 3.5 are using 2.0 runtime)
    it can be change by changing ilasmpath setting so:
    2.0 => C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ilasm.exe
    4.0 => C:\Windows\Microsoft.NET\Framework\v4.0.30319\ilasm.exe

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Selvin
Systems / Hardware Administrator
Poland Poland
No Biography provided

Comments and Discussions

 
GeneralRe: Exporting problem using the "DLLExport"-Function Pinmembersaplpete10-Dec-08 8:54 
GeneralRe: Exporting problem using the "DLLExport"-Function PinmemberSelvin10-Dec-08 12:24 
GeneralRe: Exporting problem using the "DLLExport"-Function Pinmembersaplpete11-Dec-08 11:17 
GeneralRe: Exporting problem using the "DLLExport"-Function PinmemberSelvin11-Dec-08 13:14 
GeneralRe: Exporting problem using the "DLLExport"-Function Pinmembersaplpete12-Dec-08 11:59 
QuestionRe: Exporting problem using the "DLLExport"-Function PinmemberFilip Vande Weghe15-Jul-09 2:22 
AnswerRe: Exporting problem using the "DLLExport"-Function PinmemberFilip Vande Weghe16-Jul-09 5:57 
QuestionRe: Exporting problem using the "DLLExport"-Function [modified] Pinmembermla1547-Feb-13 11:02 
AnswerRe: Exporting problem using the "DLLExport"-Function Pinmembermla1548-Feb-13 6:43 
Questionmissing dependencies PinmemberMagick9323-Sep-08 10:39 
AnswerRe: missing dependencies PinmemberSelvin24-Sep-08 1:23 
GeneralExport VB dll in Visual Studio 2008 Pinmemberpaolopagano30-Jul-08 1:19 
GeneralRe: Export VB dll in Visual Studio 2008 Pinmemberplsmith51214-Jan-09 5:16 
GeneralExport DLL in Visual Studio 2008 Pinmemberpaolopagano30-Jul-08 0:43 
Hi all,
 
I created a dll in Visual Basic using Visual Studio 2008 and I need to export the only function (Ocr) in the dll. I tried what you wrote at "http://www.codeproject.com/KB/dotnet/DllExport.aspx" to export my dll but it doesn't change when I compile it since when I use Dependecy Walker I don't see any exported method in my dll. I summarize what I did following your instructions:
 
1)I created my dll in Visual Studio 2008 as a project Class Library in Visual Basic.My dll is called Bollettino.dll. It contains only a Sub called Ocr.
 
2) I downloaded the ExportDll code and I added ExportAttribute.dll as an address in my project .
 
3) Before the Sub Ocr I added in my code the statement

ExportDllAttribute.ExportDll("Ocr()", System.Runtime.InteropServices.CallingConvention.Cdecl); _
 
ecause ExportDll.exe needs to know which functions need to be exported.
 
4) I add in Project property named "Post-build event command" the following statement
 
C:\Release\ExportDll.exe C:\Projects_VS_2008\Bollettino\Bollettino\bin\Release\Bollettino.dll /$(ConfigurationName)
 
thata represents the paths of ExportDll and of my dll
 
5) I compile my dll but it doesn't happen...Because I don't see any exported method in my dll if I use Dependency Walker.
I don't receive any error messages and I don't understand why it doesn't work.
 
What is wrong in my procedure???
Can you help me??
 
I hope that this message could be read by Slevin who is the author of the article I refers to.
 
Thanks in advance.
 
Bye

 

P.S Here is the code:
 
Public Class Class1
 

'[ExportDll("Ocr",System.Runtime.InteropServices.CallingConvention.Cdecl)]
<ExportDllAttribute.ExportDll("Ocr()", System.Runtime.InteropServices.CallingConvention.Cdecl)> _
Public Sub Ocr()
 

Dim inputFile As String = "C:\\Boll.tif"
Dim strRecText As String = ""
Dim Doc1 As MODI.Document
 

Doc1 = New MODI.Document
Doc1.Create(inputFile)
Doc1.OCR() ' this will ocr all pages of a multi-page tiff file
Doc1.Save() ' this will save the deskewed reoriented images, and the OCR text, back to the inputFile
 
For imageCounter As Integer = 0 To (Doc1.Images.Count - 1) ' work your way through each page of results
strRecText &= Doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a string
Next
 
System.IO.File.Delete("C:\\test5.txt")
 
System.IO.File.AppendAllText("C:\\test5.txt", strRecText) ' write the OCR file out to disk
'System.IO.File.Create("C:\\test2.txt", strRecText)
 

Doc1.Close() ' clean up
Doc1 = Nothing
 
End Sub
 
End Class
Questioncan works in 64 bits Pinmembermanuel.alvarez3-Jun-08 2:06 
AnswerRe: can works in 64 bits PinmemberSelvin3-Jun-08 3:10 
GeneralRe: can works in 64 bits PinmemberSelvin12-Jun-08 21:48 
GeneralRe: can works in 64 bits PinmemberZamboch9-Oct-09 9:05 
GeneralSource update PinmemberSelvin29-May-08 2:27 
Questionhow to integrate ExportdllAttribute into my class library Pinmemberk7_A28-May-08 6:52 
AnswerRe: how to integrate ExportdllAttribute into my class library PinmemberSelvin29-May-08 2:08 
GeneralA little occasion in line 21 at the file ExportDllAttribute.cs, that disables export in Cdecl format. PinmemberLesha M.12-Mar-08 0:47 
GeneralProblem: Failed policy check. Pinmemberhere_i_am_190025-Jun-07 20:26 
GeneralRe: Problem: Failed policy check. Pinmemberprivacy space23-Aug-07 23:29 
GeneralRe: Problem: Failed policy check. PinmemberGurce15-Jul-08 14:57 
GeneralRe: Problem: Failed policy check. PinmemberMember 253307921-Mar-11 12:51 
QuestionStrong name DLL - fails PinmemberStefan Vogel19-Jun-07 6:44 
AnswerRe: Strong name DLL - fails PinmemberSelvin20-Jun-07 2:14 
QuestionUse with DllMain? PinmemberXen3h21-May-07 2:08 
AnswerRe: Use with DllMain? PinmemberSelvin22-May-07 2:38 
GeneralRe: Use with DllMain? PinmemberXen3h22-May-07 2:54 
GeneralRe: Use with DllMain? PinmemberSelvin22-May-07 3:35 
GeneralRe: Use with DllMain? PinmemberXen3h22-May-07 5:30 
GeneralExport method for use by RunDll32.exe PinmemberLeo Vildosola3-Apr-07 2:19 
GeneralRe: Export method for use by RunDll32.exe PinmemberSelvin6-Apr-07 4:13 
GeneralRe: Export method for use by RunDll32.exe PinmemberLeo Vildosola6-Apr-07 4:42 
GeneralRe: Export method for use by RunDll32.exe PinmemberSelvin9-Apr-07 23:04 
GeneralRe: Export method for use by RunDll32.exe PinmemberLeo Vildosola11-Apr-07 1:07 
GeneralRe: Export method for use by RunDll32.exe Pinmemberjjao24-Jun-09 8:32 
GeneralNot working with a VB dll? [modified] PinmemberAdamDuritz998-Mar-07 23:07 
GeneralError in source code Pinmemberhal6621-Nov-06 10:43 
AnswerRe: Error in source code PinmemberSelvin21-Nov-06 23:01 
QuestionAn Example [modified] PinmemberOlric869-Nov-06 22:52 
AnswerRe: An Example PinmemberSelvin10-Nov-06 22:11 
QuestionDownload PinmemberErathus9-Nov-06 7:48 
AnswerRe: Download PinmemberSelvin9-Nov-06 21:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141220.1 | Last Updated 22 Nov 2006
Article Copyright 2006 by Selvin
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid