1
\$\begingroup\$

I have a Job that needs to take some string from main thread and use it locally.

Considering that the Job System cannot directly accept the string as an argument, is there any workaround to circumvent this limit?

Can we move the string to a NativeArray<bytes> and then repackage it back into the string inside the job and use it?

For now I just have an empty string as output from the Debug.Log below:

string myString = "string";
StringTest job = new StringTest
{
    // first I need a way to copy a string to array of bytes. 
    inStr = new NativeArray<byte>(myString.Length, Allocator.TempJob),
};
JobHandle handle =  joba.Schedule();
handle.Complete();   
public struct StringTest : IJob
{
    public NativeArray<byte> inStr;

    public void Execute(){
        string s = Encoding.ASCII.GetString(inStr.ToArray());
        Debug.Log("debug log from Job " +s);
    }
}
\$\endgroup\$
5
  • \$\begingroup\$ Did you mean to copy the data from myString into inStr? I don't see any code here that does that. If you find you need to do workarounds like this, it might be worth taking a step back and examining why the job depends on the string in the first place - maybe there could be alternative ways to achieve the same goal. \$\endgroup\$
    – DMGregory
    May 17, 2022 at 11:25
  • \$\begingroup\$ Yes , there is no copy now and it was meant to copy string in that moment . I have Job that saves data to a folder to a disc , but it is not going to be a same folder all the time so i need to pass some argument to a job so he knows to which folder to save data to . \$\endgroup\$ May 17, 2022 at 11:28
  • \$\begingroup\$ "First I need a way to copy a strong to array of bytes" - so you searched for that on StackOverflow, right? \$\endgroup\$
    – DMGregory
    May 17, 2022 at 11:35
  • \$\begingroup\$ @DMGregory Thx , it was a problem that i have did not copy data from String , so i have remade it so its actally copy String data as a Byte[] and send it back to Job. \$\endgroup\$ May 17, 2022 at 11:48
  • \$\begingroup\$ If that solved your problem, post it as an Answer below. If you still need help with something, edit your question to clarify what you need help with. \$\endgroup\$
    – DMGregory
    May 17, 2022 at 12:01

1 Answer 1

1
\$\begingroup\$

Original code does not copy data from a string to a native array of bytes. First we need to copy String data to byte[], and then pass it back to a job, like this :

string myString = "flcw";
byte[] bytes = Encoding.ASCII.GetBytes(myString);
Debug.Log("creating  Job");
StringTest job = new  StringTest job
{
    inStr = new NativeArray<byte>(bytes, Allocator.TempJob),                    
};
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .