Unity C#调用so文件

1.so源文件

1.1 NaviteCode.h

#ifndef __NativeCode_H__
#define __NativeCode_H__

#if 0
#define EXPORT_DLL __declspec(dllexport) //导出dll声明
#else
#define EXPORT_DLL 
#endif

extern "C" {
	EXPORT_DLL int MyAddFunc(int _a, int _b);
	EXPORT_DLL char* GetPkey();
	EXPORT_DLL char* GetIVkey();
}

#endif

1.2 NaviteCode.cpp

#include "NaviteCode.h"


char data[16];
extern "C" {
	int MyAddFunc(int _a, int _b)
	{
		return _a + _b;
	}

	char* GetPkey() {
		//return new char[8]{ 'a','b','c','a','s','s','s','s' };
		data[0] = 'a';
		data[1] = 'b';
		data[2] = 'c';
		data[3] = 'a';
		data[4] = 's';
		data[5] = 's';
		data[6] = 's';
		data[7] = 's';
		return data;
	}

	char* GetIVkey() {
		//return new char[16]{ '1','1','1','1','1','1','1','1','8','7','6','5','4','3','2','1' };
		data[0] = '1';
		data[1] = '1';
		data[2] = '1';
		data[3] = '1';
		data[4] = '1';
		data[5] = '1';
		data[6] = '1';
		data[7] = '1';
		data[8] = '8';
		data[9] = '7';
		data[10] = '6';
		data[11] = '5';
		data[12] = '4';
		data[13] = '3';
		data[14] = '2';
		data[15] = '1';
		return data;
	}
}

注意:用 new char 将会导致 生成的 .so 体积变大 

 

新建一个文件夹native,把 NaviteCode.h 和 NaviteCode.cpp 都丢进去,同时新建两个文件 Android.mk 和 Application.mk(ndk编译需要的文件)
Android.mk

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE     :=  NativeCode
# LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_SRC_FILES  := NaviteCode.cpp
# LOCAL_LDLIBS     := -llog -landroid
# LOCAL_CFLAGS    := -DANDROID_NDK

include $(BUILD_SHARED_LIBRARY)

生成的so全名是 libNativeCode.so,但在c#中加载还是按 NativeCode 加载

Application.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 arm64-v8a x86

cmd中cd到native目录下,运行命令编译
ndk-build NDK_PROJECT_PATH=. NDK_APPLICATION_MK=Application.mk

 

成功后会生成 libs 文件夹

复制对呀 .so  到安卓的对应文件夹

然后在c#脚本中调用下这个方法

public class testDll : MonoBehaviour {

    [DllImport("NativeCode")]
    public static extern int MyAddFunc(int x, int y);
    [DllImport("NativeCode")]
    static public extern IntPtr GetPkey();

    // Use this for initialization
    void Start () {
        int ret = MyAddFunc(200, 200);
        Debug.LogFormat("--- ret:{0}", ret);
        string key = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(GetPkey());
    }
}

 

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值