(1)testdll.h中添加如下语句:
#pragma once
extern "C" __declspec(dllexport) int calAdd(int a, int b);
extern "C" __declspec(dllexport) double calSubtract(double a, double b);
#include<opencv2/opencv.hpp>
using namespace cv;
(2)testdll.cpp中添加如下语句:
#include<opencv2/opencv.hpp>
using namespace cv;
//..\..\UnityActivate\VSActivateUnity.exe
#define EXPORT_API __declspec(dllexport)
VideoCapture my_camera;
Mat image, imageR, imageL;
int m_width = 640;
int m_height = 480;
extern "C" bool EXPORT_API openCamera()
{
bool my_open = false;
while (!my_camera.isOpened())
{
//std::cout << "Cannot open the camera!" << std::endl;
my_camera.open(0);
}
my_camera.set(CV_CAP_PROP_FRAME_WIDTH, m_width);
my_camera.set(CV_CAP_PROP_FRAME_HEIGHT, m_height);
if (my_camera.isOpened())
{
my_open = true;
}
return my_open;
}
extern "C" void EXPORT_API recieveFrame(uchar* texturePtr)
{
Mat my_frameBGR;
Mat my_frameRBG;
my_camera >> my_frameBGR;
if (my_frameBGR.data)
{
cvtColor(my_frameBGR, my_frameRBG, CV_BGR2RGB);
memcpy(texturePtr, my_frameRBG.data, my_frameRBG.cols*my_frameRBG.rows*my_frameRBG.channels()*sizeof(uchar));
}
}
extern "C" void EXPORT_API closeCamera()
{
if (my_camera.isOpened())
{
my_camera.release();
}
}
在Unity中编写C#脚本如下,挂在GameObject上
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;//用c++中dll文件需要引入
public class dll : MonoBehaviour {
[DllImport("dllUnity")]
public static extern bool openCamera();
[DllImport("dllUnity")]
public static extern void recieveFrame(byte[] imageData);
[DllImport("dllUnity")]
public static extern void closeCamera();
public bool IsOpen = false;
public byte[] imageData;
public Texture2D tex;
public int Width = 640;
public int Length = 480;
// Use this for initialization
void Start ()
{
//open one camera
IsOpen = openCamera();
if (IsOpen)
{
imageData = new byte[Length * Width * 3];
tex = new Texture2D(Width, Length, TextureFormat.RGB24, false);
}
}
// Update is called once per frame
void Update ()
{
//update one camera
if (IsOpen)
{
recieveFrame(imageData);
tex.LoadRawTextureData(imageData);
tex.Apply();
GetComponent<Renderer>().material.mainTexture = tex;
}
}
void OnGUI()
{
if (!IsOpen)
{
//string myword = "打开相机失败!";
string myword = "camera pause for a while!";
GUI.TextArea(new Rect(200,100,200,50),myword,new GUIStyle());
}
//to get the button
GUI.color = Color.yellow;
GUI.backgroundColor = Color.red;
if(GUI.Button(new Rect(20,50,60,30), "continue"))
{
IsOpen = true;
}
GUI.color = Color.white;
GUI.backgroundColor = Color.green;
if(GUI.Button(new Rect(20,100,60,30), "pause"))
{
IsOpen = false;
}
GUI.color = Color.white;
GUI.backgroundColor = Color.blue;
if(GUI.Button(new Rect(20,150,60,30), "close"))
{
closeCamera();
}
}
}
Unity设置:
提示:C#脚本中的dllUnity要与创建的dll文件名称保持一致哦