0

I would like to call a method in a dll whose code is written in C from my C # code but I can't do that. The error message is:

Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at DisplayMessageDLL.Program.dividetwo(Int32 a, Int32 b, Int32* res) at DisplayMessageDLL.Program.Main(String[] args) in c:\Users\mat\Documents\Visual Studio 2013\Projects\DisplayMessageFromDLL\ConsoleApplication1\Program.cs:line 30 Press any key to continue . . .

In fact, the dll is generated with the following command line in the Windows console: R CMD SHLIB --preclean simple.c

Code of simple.c class is:

void dividetwo(int a, int b, int *result)
{
*result = a/b;
}
void Rdividetwo(int *a, int *b, int *result)
{
dividetwo(*a, *b, result);
}

and my C# code that calls dividetwo() method is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using RDotNet;
using RDotNet.NativeLibrary;
using RDotNet.Utilities;
using RDotNet.Internals;
using RDotNet.Dynamic;
using RDotNet.Diagnostics;
using RDotNet.Devices;

namespace DisplayMessageDLL
{
    class Program
    {
        [DllImport("C:/rdoc/simple.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
        unsafe public static extern void dividetwo(int a, int b, int* res); // DLL support

        unsafe static void Main(string[] args)
        {
            int a = 25, b = 25;
            int res = 0;

            dividetwo(a, b, &res);
            Console.WriteLine("Result of " +a+ " / " +b+ " = " + res);

            Console.Read();

        }
    }
}

Why isn't the dll generated by the command 'R CMD SHLIB simple.c' accessible from my C# code? Whereas if I generate a dll in Visual Studio 2013 from the same code, this dll is accessible for my C # code.

Sam Firke
  • 21,571
  • 9
  • 87
  • 105
Mat
  • 13
  • 2
  • I know absolutely nothing about R, but does it actually create a valid Windows executable? If you know that for a fact, then could it be something as simple as processor architecture mismatch (which is the most common reason I've seen for that exception)? – James R. Jun 02 '15 at 20:34
  • It is a dup of [this](http://stackoverflow.com/questions/30602151/system-badimageformatexception-while-trying-to-call-c-dll-from-c-sharp-code) or [this one](http://stackoverflow.com/questions/2728560/badimageformatexception-when-loading-32-bit-dll-target-is-x86) – CristiFati Jun 02 '15 at 21:03

0 Answers0