C++制作Android版so库给Unity使用

上篇介绍Windows版dll文件制作与在Unity中调用,本篇介绍Android版so文件制作以及在Unity项目中使用。

生成so库文件,需要借助NDK工具,并且需要配置环境变量。配置可参考https://www.jianshu.com/p/c3e1fe6f61c4

NDK配置完成后,先讲解so文件制作的整个过程。

1)测试脚本文件创建:

 头文件MathDll.h【注意】if 0

#if 0
# define _DLLExport __declspec (dllexport) //定义该函数的dll
# else  
# define _DLLExport   //使用该函数
#endif  

//代表c风格的
extern "C"  int _DLLExport Add(int x, int y);

extern "C"  int _DLLExport Max(int x, int y);

实现文件MathDll.cpp

#include <stdio.h>//引入C的库函数
#include "MathDll.h"

//宏定义  
#define  EXPORTBUILD 

//相加
int _DLLExport Add(int x, int y)
{
	return x + y;
}

//取较大的值
int _DLLExport Max(int x, int y)
{
	return (x >= y) ? x : y;
}

2)Android.mk文件创建

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
 
LOCAL_MODULE     :=  MathDll
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES  :=  MathDll.cpp
LOCAL_LDLIBS     := -llog -landroid
LOCAL_CFLAGS    := -DANDROID_NDK
 
include $(BUILD_SHARED_LIBRARY)

3)Apllication.mk文件创建

APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -std=c++11
APP_PLATFORM := android-19
APP_CFLAGS += -Wno-error=format-security
APP_BUILD_SCRIPT := Android.mk
APP_ABI := armeabi-v7a x86

4)新建一个文件夹,将上述4份文件放入

5)运行cmd命令:先cdj进入该文件夹,然后执行命令:

ndk-build NDK_PROJECT_PATH=. NDK_APPLICATION_MK=Application.mk 

 

 后生成libs文件和obj文件。至此关于C++代码生成so文件库过程完成。

接下来导入Unity项目工程测试使用。

1)先将libs文件夹所有文件复制到Assets/Plugins/Android/文件夹下

2)建测试脚本DllTest.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;

public class DllTest : MonoBehaviour {

    public Text text1;
    public Text text2;

    [DllImport("MathDll")]
    private static extern int Add(int x, int y);
    [DllImport("MathDll")]
    private static extern int Max(int x, int y);


    // Use this for initialization
    void Start()
    {

        int c = Add(3, 7);
        Debug.Log("c = " + c);
        text1.text = "c = " + c;

        int max = Max(7, 12);
        Debug.Log("max = " + max);
        text2.text = "max = " + max;
    }

    // Update is called once per frame
    void Update()
    {

    }
}

 3)编辑器不能测试,打出apk来测试,安装运行结果如下:

 至此,关于C++制作Android版so库文件供Unity使用全过程介绍完成。

Guess you like

Origin blog.csdn.net/hppyw/article/details/119538496
Recommended