C# & C++ Error

Discussion in 'Computer Programming, Emulation, and Game Modding' started by gudenau, Dec 24, 2016.

Dec 24, 2016

C# & C++ Error by gudenau at 6:34 PM (178 Views / 0 Likes) 0 replies

  1. gudenau
    OP

    Member gudenau Never a unique idea

    Joined:
    Jul 7, 2010
    Messages:
    3,118
    Location:
    /dev/random
    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?
     

Share This Page