27 April 2016
版权声明:本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名elloop(包含链接)

前言

本文分享一个实用的python脚本,用来在cocos2d-x打android包的时候,添加C++源文件路径到jni/Android.mk中。

注意:脚本所在目录为使用cocos new创建的工程的proj.android路径下。此路径下有一个jni目录,脚本的作用就是修改jni/Android.mk文件的 `LOCAL_SRC_FILES` 字段

add_cpp_paths.py

# coding=utf-8

import os
import sys

reload(sys)
sys.setdefaultencoding('utf8')

def cpp_filter(f_name):
    return f_name.endswith(".cpp")

def get_dir_tree(begin_dir, coll, file_filter=None):
    files = os.listdir(begin_dir)
    for file_name in files:
        full_path = os.path.join(begin_dir, file_name)
        if os.path.isdir(full_path):
            get_dir_tree(full_path, coll)
        else:
            if file_filter != None:
                if file_filter(full_path):
                    coll.append(full_path)
            else:
                coll.append(full_path)

def get_all_cpp_sources_relative_path(cpp_files, cpp_root_dir, jni_dir):
    get_dir_tree(cpp_root_dir, cpp_files, cpp_filter)
    os.chdir(jni_dir)
    for i in range(len(cpp_files)):
        if i < len(cpp_files) - 1:
            cpp_files[i] = "\t" + os.path.relpath(cpp_files[i], os.curdir) + " \\\n"
        else:
            cpp_files[i] = "\t" + os.path.relpath(cpp_files[i], os.curdir) + "\n"

if "__main__" == __name__:
    original_cwd = os.getcwd()

    cppfiles = ["hellocpp/main.cpp"]

    # cpp files in Classes folder.
    cpp_source_root_dir = os.getcwd() + os.sep + os.pardir + os.sep + "Classes"
    jni_root_dir        = os.getcwd() + os.sep + "jni"
    get_all_cpp_sources_relative_path(cppfiles, cpp_source_root_dir, jni_root_dir)

    os.chdir(original_cwd)

    # read original contents of jni/Android.mk
    with open("jni/Android.mk", "r") as f:
        mk_contents = f.readlines()

    # substitue LOCAL_SRC_FILES field.
    line_number_of_src_files = 0
    for i in range(len(mk_contents)):
        if mk_contents[i][0] != '#' and "LOCAL_SRC_FILES" in mk_contents[i]:
            line_number_of_src_files = i
            mk_contents[i] = "LOCAL_SRC_FILES := \\\n"
            for cpp_s in cppfiles:
                mk_contents[i] += cpp_s
            mk_contents[i] += "\n"
            break
    
    for i in range(line_number_of_src_files+1, len(mk_contents)):
        if "=" not in mk_contents[i]:
            mk_contents[i] = ""
        else:
            break

    # overwrite the original mk file.
    with open("jni/Android.mk", "w") as f:
        f.writelines(mk_contents)

    os.system("pause")

在这里也能看到这篇文章:github博客, CSDN博客, 欢迎访问



分享到