KenGey
KenGey

Reputation: 406

creating C .dll and using it in C#

As a C# developper I'm trying to learn some C now. It seemed me fun to create a C dll and then use the functions I created in a C# project, just to get familiar with the language.

For developping the c dll I use DEV-C++ and obviously for C# Visual Studio.

This is what I've come up with so far:

C

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#define NAG_CALL __stdcall 
#define NAG_DLL_EXPIMP  __declspec(dllexport)

NAG_DLL_EXPIMP void NAG_CALL Scalars(double, double*);
NAG_DLL_EXPIMP void NAG_CALL Scalars(double in, double *out)
{
  *out = in;
}

And in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace TestMyOwnCDLL
{
    public static class MyCDLLWrapper
    {
        [DllImport("TestDLL1.dll")]
        private static extern void Scalars(double invar, ref double outvar);

        public static double CallScalars(double invar)
        {
            double outvar = (double)0.0;
            Scalars(invar, ref outvar);
            return outvar;
        }

    }
}

I've added TastDLL1.dll to the assembly and marked 'Always copy'. However, when calling the function i get a BadImageFormatException. This means that the dll is found but it can't execute the dll for some reason.

Any ideas? I've used the examples from: http://www.drdobbs.com/cpp/calling-c-library-dlls-from-c/184406285

Kind regards.

Upvotes: 0

Views: 479

Answers (1)

KenGey
KenGey

Reputation: 406

Solved the error: The DEVC++ compiler compiles in x64 while the target platform for the c# Application was set to be x86. Changing the target platform to x64 solves the error.

Now, Is there a possibility to compile to AnyCPU for C dll's?

Upvotes: 1

Related Questions