Hello all. I’m trying to make use of a C program compiled to dll through Unity C#.
The code is rather simple, yet it doesn’t work.
When putting this on an object in Unity, running produces a Unity crash. I suspect it has to do with the malloc in the C code, as if I had simply char* ptr = “Hello World” Unity doesn’t crash, but I only get junk. I never get the string from C. Also, I recognize that I will have to free the memory allocated by the C program , but I will add that later.
Where have I gone wrong with this? I have the malloc in there because this is a test for a library which allocates some space and returns char*.
Thank you for your help with this.
testdll.h
#ifdef TESTDLL_EXPORTS
#define TESTDLL_API __declspec(dllexport)
#else
#define TESTDLL_API __declspec(dllimport)
#endif
TESTDLL_API char* fntestdll(void);
testdll.c
#include "pch.h"
#include "framework.h"
#include "testdll.h"
// This is an example of an exported function.
TESTDLL_API char* fntestdll(void)
{
char* ptr = (char*)malloc(sizeof(char) * 12);
strcpy_s(ptr, 12, "Hello World");
return ptr;
}
Within Unity, UseTestDll.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;
using System;
public class UseTestDll : MonoBehaviour
{
#if UNITY_IPHONE
[DllImport ("__Internal")]
#else
[DllImport("testdll")]
#endif
private static extern IntPtr fntestdll();
void Awake()
{
IntPtr ptr = IntPtr.Zero;
ptr = fntestdll();
string results = Marshal.PtrToStringAnsi(ptr);
Debug.Log(results);
}
}