3

I am trying to get SWIG to work with Visual Studio and C#.

I downloaded swigwin-2.0.4.zip and converted the project to a VS 2010 project.

I am able to build the 'class' example. When I then try to run compiled build I get the error

    The type initializer for 'examplePINVOKE' threw an exception.

I haved googled the error, but have not found any suggestions on how to resolve it.

Hope somebody is able to help!

Thanks,

Christian

Christian Bøhlke
  • 779
  • 1
  • 7
  • 18

3 Answers3

3

What worked for me was to:

  1. Go to Build->Configuration Manager. For the C# project change AnyCpu to x86 and rebuild.
  2. Copy example.dll to bin\x86\Debug (Release).

Doesn't require CorFlags.

pbalaga
  • 2,018
  • 1
  • 21
  • 33
  • Seconded. I was also able to recreate the 'type initializer' exception by changing my build configuration for swig from 'x86' to 'AnyCpu'. Reverting back to 'x86' and the program ran fine with no exceptions. . – AndyUK Aug 27 '17 at 19:56
1

I got the following answer from Gregory Bronner on the swig-user mailinglist:

    I had this issue as well (VS2010 , Windows 7, 64 bit computer, 32 bit mode dll, .NET 4) :

    The problem actually relates to being unable to load the DLLs

    There were two causes:

    #1:  All DLLs used by the C# assembly need to be in the same directory (or you need to change the lookup paths).


    #2: The C# or the C++ DLL (I forget which) had incorrect CofFlags -- use CorFlags  /32Bit+ *.dll or something like that.  You could also try using /UpgradeCLRHeader


    #3: You need to target the .NET 4.0 system in the project file, but 1 and 2 should get you started.

I will try these hints out and see whether they work and then post an answer if I am able to resolve the issue.

Christian Bøhlke
  • 779
  • 1
  • 7
  • 18
1

The solution for me was

  • Move the used dll's to the Release (or Debug) directory
  • Run CorFlags /32Bit+ file.exe

where file.exe is the executable produced by building the code.

For more information on what is going on Í found the following links helpful

http://www.davesquared.net/2008/12/systembadimageformatexception-on-64-bit.html

http://blogs.msdn.com/b/joshwil/archive/2005/05/06/415191.aspx

Christian Bøhlke
  • 779
  • 1
  • 7
  • 18