Skip to content

[Feature] - ConstantDataSequential does not have a way of accessing non-string data #200

@spacehamster

Description

@spacehamster

Is your feature request related to a problem? Please describe.
ConstantDataArray are sometimes used to store binary blobs and there is no built-in way to access the raw data in those cases.

Describe the solution you'd like
A built in ConstantDataArray.getRawDataValues method

Describe alternatives you've considered
I have been using this method to access the data

[SuppressUnmanagedCodeSecurity]
[DllImport("Ubiquity.NET.LibLLVM", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr LLVMGetAsString(LLVMValueRef c, out size_t Length);

public static byte[] GetRawBytes(this ConstantDataSequential value)
{
	var valueHandle = (LLVMValueRef)typeof(Value)
		.GetProperty("ValueHandle", BindingFlags.Instance | BindingFlags.NonPublic)
		.GetValue(value);
	var charPtr = LLVMGetAsString(valueHandle, out var length);
	var result = new byte[length];
	Marshal.Copy(charPtr, result, 0, length);
	return result;
}

I've also considered something like this that would prevent a second copy of the byte array to a different typed array, but I did not require it for my use case.

public static unsafe T[] GetData<T>(this ConstantDataSequential value) where T : unmanaged
{
	var valueHandle = (LLVMValueRef)typeof(Value)
		.GetProperty("ValueHandle", BindingFlags.Instance | BindingFlags.NonPublic)
		.GetValue(value);
	var charPtr = LLVMGetAsString(valueHandle, out var length);
	var result = new T[length / Marshal.SizeOf<T>()];
	fixed(T* ptr = result)
	{
		Buffer.MemoryCopy(charPtr.ToPointer(), ptr, length, length);
	}
	return result;
}

Additional context
The default LLVMGetAsString returns a managed string and ConstantDataSequential.getRawDataValues returns a StringRef, but LLVM seems to use char pointers and StringRefs for both strings and non-string binary data.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions