1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでC/C++から文字列配列を持ってくる

Last updated at Posted at 2021-12-22

以下見てもわからなかったので
https://qiita.com/everylittle/items/6e18ba23f38502c18f3e

C/C++だとこんな感じのをpythonから見れるようにする

char** list = 0;
int32_t column_num = get_list(&list, false);
print_list(list, column_num);
if (list) free(list);

void print_list(char** list, int column_num) {
    FILE* fp = fopen("D:\\test.txt", "w");
    if (!fp) goto error;
    for (int i = 0; list[i]; i++) {
        fprintf(fp, "%s", list[i]);
        if (i % column_num == (column_num - 1)) {
            fprintf(fp, "\n");
        }
        else {
            fprintf(fp, "\t");
        }
    }
error:
    if (fp) fclose(fp);
}

pythonの場合

pp = c_char_p()
# argtypeやrestypeの指定は必要無かった
column_num = g.dll.get_list(byref(pp), c_bool(False))
out_data = cast(pp, POINTER(c_char_p))

count = 0
flag = True
while(flag):
    for i in range(column_num):
        p = cast(out_data[count], c_char_p)
        if p.value is None:
            flag = False
            break
        # バイト配列を一回変数に落とさないと自動変換が走ってしまう
        b = p.value
        print(b.decode(), end='\t')
        count = count+1
    print("")

# pythonから解放は無理っぽい
if pp.value is not None:
    g.dll.allocate_free(pp)

pythonの方が冗長だけどプロの人が書いたらもっとすっきりするんだろう。たぶん

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?