erlang nif小结

一、nif获取string参数的两种方式

1、eif_get_string

实例如下:

 static ERL_NIF_TERM erl_sm4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{ unsigned int input_len = 0;
unsigned int key_len = 1024;
char key_string[1024] = {0}; int output_len = sizeof(buff);
enif_get_list_length(env, argv[0],&input_len); char *input_string = NULL;
if (input_len <= 1)
input_len = 2018;
else
input_len = input_len +1; input_string = (char*)malloc(input_len);
memset(input_string,0x00,input_len); enif_get_string(env,argv[0],input_string,input_len, ERL_NIF_LATIN1);
enif_get_string(env,argv[1],key_string,key_len, ERL_NIF_LATIN1);
printf("input_string=%s,input_len=%d,key_string=%s,key_len=%d\n", input_string,input_len,key_string,key_len);
SM4_KEY iKey;
sm4_SetKey(&iKey, (unsigned char *)key_string, 1);
printf("ERK=%s,DRK=%s,MK=%s\n", iKey.ERK,iKey.DRK,iKey.MK);
enin_sm4((unsigned char*)input_string,input_len,buff,&output_len, &iKey, 1);
memset(buff+output_len,0x00,sizeof(buff)-output_len); free(input_string);
input_string = NULL;
return enif_make_string_len(env, (const char *)buff, output_len,ERL_NIF_LATIN1);
}

2、enif_inspect_iolist_as_binary

 static ERL_NIF_TERM erl_sm4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
ErlNifBinary ebinary_input,ebinary_key; if (!enif_inspect_iolist_as_binary(env, argv[0], &ebinary_input) ||
!enif_inspect_iolist_as_binary(env, argv[1], &ebinary_key)){ return enif_make_badarg(env);
} int key_len = ebinary_key.size;
int input_len = ebinary_input.size;
int output_len = sizeof(buff); unsigned char *input_string = (unsigned char*)malloc(input_len+1);
unsigned char *key_string = (unsigned char*)malloc(key_len+1); 18 memcpy(input_string, ebinary_input.data, input_len);
19 memcpy(key_string, ebinary_input.data, key_len);
//printf("input_string=%s,input_len=%d,key_string=%s,key_len=%d\n", input_string,input_len,key_string,key_len); SM4_KEY iKey;
sm4_SetKey(&iKey, key_string, 1); memset(buff,0x00,sizeof(buff));
enin_sm4(input_string,input_len,buff,&output_len, &iKey, 1);
memset(buff+output_len,'\0',sizeof(buff)-output_len); free(input_string);
free(key_string);
return enif_make_string_len(env, (const char *)buff, output_len,ERL_NIF_LATIN1);
}

二、nif返回string的两种方式

1、enif_make_string

ERL_NIF_TERM enif_make_string(ErlNifEnv* env, const char* string, ErlNifCharEncoding encoding)

返回一个以空字符结尾的string

2、enif_make_string_len

ERL_NIF_TERM enif_make_string_len(ErlNifEnv* env, const char* string, size_t len, ErlNifCharEncoding encoding)

返回一个长度为len的字符串string,空字符当做普通字符处理

上一篇:ORA-00933 UNION 与 ORDER BY


下一篇:Android 第三方开源库收集整理(转)