Switched FFI internals from IntPtrs to SafeHandles.

Also improvements to T4 codegen helpers.