3

I'm writing some Erlang code that basically accepts some binary data from a TCP connection and then uses a C nif to decrypt the data and return the decrypted data.

The problem is that I can't seem to figure out how to modify the passed in binary.

This is the function I'm using. If anyone can point me in the right direction, I would appreciate it.

static ERL_NIF_TERM decrypt(ErlNifEnv* env, ErlNifBinary *data);

Thanks!

Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
tkblackbelt
  • 391
  • 2
  • 10
  • 6
    Are you confident that _modifying_ the binary is the right approach? It is my understanding that binaries may be pooled in the VM, and modifying one binary may in fact modify "unrelated" data. Why not return a new binary? – sarnold Jul 04 '12 at 01:28

1 Answers1

4

You cannot modify a passed binary. You need to make a copy first and modify the copied binary, then return the copied (=modified) binary back to the caller.

Remember binary is allocated in a shared heap; if you overwrite the original you'll be in trouble because that breaks the principle of single assignment of Erlang.

See an example of handling binary arguments in sfmt-erlang NIF code for the details.

jj1bdx
  • 1,117
  • 1
  • 15
  • 32