C# & C++ Error

gudenau

Largely ignored
OP
Member
Joined
Jul 7, 2010
Messages
3,882
Trophies
2
Location
/dev/random
Website
www.gudenau.net
XP
5,381
Country
United States
I am working on a project that requires the use of C++ from C# code, but I am running into a problem. The pointer I am passing is getting corrupted somehow causing illegal memory accesses.

C++
Code:
#include <malloc.h>

#define API extern "C" __declspec(dllexport)

API void __cdecl allocNative(void *instance) {
    instance = malloc(8);
}

API void __cdecl freeNative(void *instance) {
    free(instance);
    instance = NULL;
}

C#
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.InteropServices;

namespace NativeTest
{
    class Program
    {
        //TODO Make this better
        const string dllName = "fullDllPathRemoved.dll";

        [DllImport(dllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        private extern static int allocNative(out IntPtr instance);

        [DllImport(dllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        private extern static int freeNative(ref IntPtr instance);

        static void Main(string[] args)
        {
            IntPtr instance;
            allocNative(out instance);
            freeNative(ref instance);
        }
    }
}

Any idea what I need to do differently?
 

Site & Scene News

Popular threads in this forum

General chit-chat
Help Users
    K3Nv2 @ K3Nv2: So negative