一、nif获取string参数的两种方式
1、eif_get_string
实例如下:
1 static ERL_NIF_TERM erl_sm4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 2 { 3 4 unsigned int input_len = 0; 5 unsigned int key_len = 1024; 6 char key_string[1024] = {0}; 7 8 int output_len = sizeof(buff); 9 enif_get_list_length(env, argv[0],&input_len); 10 11 char *input_string = NULL; 12 if (input_len <= 1) 13 input_len = 2018; 14 else 15 input_len = input_len +1; 16 17 input_string = (char*)malloc(input_len); 18 memset(input_string,0x00,input_len); 19 20 enif_get_string(env,argv[0],input_string,input_len, ERL_NIF_LATIN1); 21 enif_get_string(env,argv[1],key_string,key_len, ERL_NIF_LATIN1); 22 printf("input_string=%s,input_len=%d,key_string=%s,key_len=%d ", input_string,input_len,key_string,key_len); 23 SM4_KEY iKey; 24 sm4_SetKey(&iKey, (unsigned char *)key_string, 1); 25 printf("ERK=%s,DRK=%s,MK=%s ", iKey.ERK,iKey.DRK,iKey.MK); 26 enin_sm4((unsigned char*)input_string,input_len,buff,&output_len, &iKey, 1); 27 memset(buff+output_len,0x00,sizeof(buff)-output_len); 28 29 free(input_string); 30 input_string = NULL; 31 return enif_make_string_len(env, (const char *)buff, output_len,ERL_NIF_LATIN1); 32 }
2、enif_inspect_iolist_as_binary
1 static ERL_NIF_TERM erl_sm4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) 2 { 3 ErlNifBinary ebinary_input,ebinary_key; 4 5 if (!enif_inspect_iolist_as_binary(env, argv[0], &ebinary_input) || 6 !enif_inspect_iolist_as_binary(env, argv[1], &ebinary_key)){ 7 8 return enif_make_badarg(env); 9 } 10 11 int key_len = ebinary_key.size; 12 int input_len = ebinary_input.size; 13 int output_len = sizeof(buff); 14 15 unsigned char *input_string = (unsigned char*)malloc(input_len+1); 16 unsigned char *key_string = (unsigned char*)malloc(key_len+1); 17 18 memcpy(input_string, ebinary_input.data, input_len); 19 memcpy(key_string, ebinary_input.data, key_len); 20 //printf("input_string=%s,input_len=%d,key_string=%s,key_len=%d ", input_string,input_len,key_string,key_len); 21 22 SM4_KEY iKey; 23 sm4_SetKey(&iKey, key_string, 1); 24 25 memset(buff,0x00,sizeof(buff)); 26 enin_sm4(input_string,input_len,buff,&output_len, &iKey, 1); 27 memset(buff+output_len,' ',sizeof(buff)-output_len); 28 34 free(input_string); 35 free(key_string);
36 return enif_make_string_len(env, (const char *)buff, output_len,ERL_NIF_LATIN1); 37 }
二、nif返回string的两种方式
1、enif_make_string
ERL_NIF_TERM enif_make_string(ErlNifEnv* env, const char* string, ErlNifCharEncoding encoding)
返回一个以空字符结尾的string
ERL_NIF_TERM enif_make_string_len(ErlNifEnv* env, const char* string, size_t len, ErlNifCharEncoding encoding)
返回一个长度为len的字符串string,空字符当做普通字符处理