#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
#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());
}
}