Hello I am trying to test the functionality of Unity’s plugin system. So far I can get a simple adding function, but I have having serious issues trying to send and receive string values.
My Unity C# Code looks like this:
//GUIctrl.cs
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.InteropServices;
public class GUIctrl : MonoBehaviour {
[DllImport ("dllTest")] private static extern string MyMathFloatCatBat(string str);
[DllImport ("dllTest")] private static extern string MyMathFloatThrough(string str);
public string txInVal1;
public string txInVal2;
public string txOutval1;
public string txOutval2;
// Use this for initialization
void Start () {
txInVal1 = "Text1";
txInVal2 = "Text2";
}
// Update is called once per frame
void Update () {
}
/// I am the GUI Rendering function. I draw the text boxes and buttons.
void OnGUI(){
Rect drawPos;
// draw text boxes for input
drawPos = new Rect(5,5,100,50);
txInVal1 = GUI.TextField(drawPos, txInVal1);
drawPos = new Rect(125,5,100,50);
txInVal2 = GUI.TextField(drawPos, txInVal2);
drawPos = new Rect(5,65,100,50);
if(GUI.Button(drawPos, "submit")){
txOutval1 = MyMathFloatThrough(txInVal1);
txOutval2 = MyMathFloatCatBat(txInVal2);
}
// draw text boxes for output
drawPos = new Rect(5,165,100,50);
txOutval1 = GUI.TextField(drawPos, txOutval1);
drawPos = new Rect(125,165,100,50);
txOutval2 = GUI.TextField(drawPos, txOutval2);
}
}
My C++ code , which is set to complie to a dll in VS 2005 looks like this:
// myMathFunc.h
#ifndef _MY_MATH_FUNC_H_
#define _MY_MATH_FUNC_H_
#include <stdio.h>
#include <windows.h>
#include <string.h>
extern "C" __declspec(dllexport) int MyMathIntAdd(int x, int y);
extern "C" __declspec(dllexport) BSTR MyMathFloatCatBat(BSTR inVal);
extern "C" __declspec(dllexport) BSTR MyMathFloatThrough(BSTR inVal);
#endif
// myMathFunc.cpp
#include "myMathFunc.h"
#include <string.h>
extern "C" __declspec(dllexport)
int MyMathIntAdd(int x, int y){
return x+y;
}
extern "C" __declspec(dllexport)
BSTR MyMathFloatCatBat(BSTR inVal){
return SysAllocString(L"Hello World");
}
extern "C" __declspec(dllexport)
BSTR MyMathFloatThrough(BSTR inVal){
if(inVal[0] == 'X'){
inVal = SysAllocString(L"goodbye");
}
return inVal;
}
The function MyMathFloatThrough(string str) returns the entire string that was passed to it (so I know I can get a full string back from the dll), but the function MyMathFloatCatBat(string str) returns just the first letter of the string we are trying to make. I am trying to make a function that can take in a string does some computations on it then return that string. But first I need to be able to return a string that was generated in the dll.
Thanks for your help.