C言語の構造体のデータをPerlから操作したい。

C言語の構造体のデータをPerlから操作したい。

C言語の構造体のデータをバイナリのままファイルに吐き出して、Perlで読み書きしてからそのファイルを構造体に戻す。

元の構造体のヘッダ

typedef struct __TEST_STRUCT{
	int n1, n2, n3;
	char txt[16];
} TEST_STRUCT;

構造体のデータをファイルに書き出すC言語のコード

#include <stdio.h>
#include <string.h>

#include "test.h"

int main(int argc, char** argv){
	TEST_STRUCT test;
	memset(&test, 0, sizeof(test));
	test.n1 = 1;
	test.n2 = 0x12345678;
	test.n3 = -1;
	snprintf(&test.txt[0], sizeof(test.txt), "hello,world.\n");

	FILE* fp = fopen("test.dat", "wb");
	if(!fp){ return 0; }

	fwrite(&test, sizeof(test), 1, fp);

	fclose(fp);
}

バイナリファイルを読み出すPerlのコード

#!/usr/bin/perl -w

use strict;

eval{
	main(@ARGV);
};

print $@ if $@;

sub main{
	open my $f, '<', 'test.dat' or die "can't open test.dat.";
	binmode $f;
	my $sz = read $f, my $buf, 28;
	print "$sz\n";
	my ($n1,$n2,$n3,$txt) = unpack "lllZ16", $buf;
	print "$n1,$n2,$n3,$txt\n";
}

バイナリファイルに書き出すPerlのコード

#!/usr/bin/perl -w

use strict;

eval{
	main(@ARGV);
};

print $@ if $@;

sub main{
	open my $f, '<', 'test.dat' or die "can't open test.dat.";
	binmode $f;
	my $sz = read $f, my $buf, 28;
	print "$sz\n";
	my ($n1,$n2,$n3,$txt) = unpack "lllZ16", $buf;
	print "$n1,$n2,$n3,$txt\n";
}

ファイルに書き出された構造体のデータを読み出すC言語のコード

#include <stdio.h>
#include <string.h>

#include "test.h"

int main(int argc, char** argv){
	TEST_STRUCT test;
	memset(&test, 0, sizeof(test));

	FILE* fp = fopen("test.dat", "rb");
	if(!fp){ return 0; }

	fread(&test, sizeof(test), 1, fp);

	fclose(fp);

	printf(
		"n1:%d\n"
		"n2:%d\n"
		"n3:%d\n"
		"txt:%s\n",
		test.n1,
		test.n2,
		test.n3,
		test.txt
		);
}