Why doesn’t an ordered object save the values ​​changed inside the native code?

I am sure there is a simple answer, but I could not find it after some research. I read and proved (unless I wrote) incorrectly that the automatically distributed structure passed by reference (or classes) allocated in managed memory is correctly read and written using native code, however, as soon as the code execution returns to the managed level , values ​​changed inside the native code are not saved. Here is an example:

    [StructLayout(LayoutKind.Sequential, Pack = 1)]
public class DirtyWordsCheckResult
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
    public string replace_string;
    public EnumDirtyWordsType dirty_type;

    public DirtyWordsCheckResult()
    {
        replace_string = new string(' ', 1024);
    }
}

public enum EnumDirtyWordsType
{
    kDirtyWordsTypeNormalAllowWords = 0,   // normal allow words
    kDirtyWordsTypeEvil = 1,               // illegal,can not be displayed
    kDirtyWordsTypeSensitive = 2,          // legal, but contain sensitive
}

public override EResult DirtyWordsFilter(string words, bool replace_sensitive, out DirtyWordsCheckResult check_result)
{
    check_result = new DirtyWordsCheckResult();
    var result = Utils.DirtyWordsFilter(utils_, words, replace_sensitive, check_result);
    return result;
}

the built-in function DirtyWordsFilter correctly receives the selected object and can write in it without problems, however, the values ​​are not saved.

, Marshal.AllocHGlobal IntPTR, , , .

+4
1

blittable. , , . . - CharSet, .NET , char []. , pinvoke , , .

. [Out] , . [DllImport], :

[DllImport(...)]
private static extern EResult DirtyWordsFilter(..., [Out] DirtyWordsCheckResult check_result);  

pinvoke , ref out ( ). , , [In] . , . Fwiw, , Pack = 1 , , , - 8. , .

+5

Source: https://habr.com/ru/post/1676261/


All Articles