UnityC#调用so文件


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

    #endif

1.2 NaviteCode.cpp

    #include "NaviteCode.h"
    #include <cstring>
    using namespace std;

    extern "C" {
        int MyAddFunc(int _a, int _b)
        {
            return _a + _b;
        }

        // static char* key = "aShLdS$u3p@V-btd5dKmQZdwa";
		
        char buff[255]; 
        char* GetAppKey()
        {
            strcpy(buff,"aShLdS$u3p@V-btd5dKmQZdwa");
            return buff;
		    //return "aShLdS$u3p@V-btd5dKmQZdwa";
        }

}

2.调用方法

将上述生成的so文件放在Plugins-Android下

using System;
using System.Runtime.InteropServices;

public class Jni
{
    [DllImport("NativeCode")]
    public static extern IntPtr GetAppKey();
}

public class Usage
{
    private string GetAppKey()
    {
        IntPtr keyPtr = Jni.GetAppKey();
        string appKey = Marshal.PtrToStringAnsi(keyPtr);
        Debug.Log("Login result:Get appKey " + appKey);

        return appKey;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Visual Studio 中调用 .so 文件,需要使用外部函数声明方式,即在 C/C++ 代码中声明外部函数,然后通过动态链接库的方式将 .so 文件与应用程序链接起来。 以下是一些基本的步骤: 1. 编写 C/C++ 源代码,包含对 .so 文件中函数的声明。 2. 通过动态链接库(.dll 或 .so 文件)来提供实现。 3. 在程序中使用 LoadLibrary() 函数加载动态链接库。 4. 使用 GetProcAddress() 函数获取动态链接库中函数的地址。 5. 调用动态链接库中的函数。 以下是一个简单的示例程序: ```c #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> // 声明外部函数 typedef int (*add_func)(int, int); int main() { void* handle; add_func add; int a, b, c; // 打开动态链接库 handle = dlopen("./libtest.so", RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); exit(EXIT_FAILURE); } // 获取函数地址 add = (add_func) dlsym(handle, "add"); if (!add) { fprintf(stderr, "%s\n", dlerror()); exit(EXIT_FAILURE); } // 调用函数 a = 10; b = 20; c = add(a, b); printf("%d + %d = %d\n", a, b, c); // 关闭动态链接库 dlclose(handle); return 0; } ``` 在这个例子中,我们声明了一个名为 `add` 的外部函数,并在程序中使用 `dlopen()` 函数打开了名为 `libtest.so` 的动态链接库文件。然后使用 `dlsym()` 函数获取 `add()` 函数的地址,并调用它。最后,使用 `dlclose()` 函数关闭动态链接库文件。 注意,以上代码中的 `dlopen()`、`dlsym()`、`dlclose()` 等函数是 Linux 系统下的动态链接库操作函数。在 Windows 系统下使用相应的函数来加载和使用 DLL 文件

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值