powered by simpleCommunicator - 2.0.52     © 2025 Programmizd 02
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Структура и Marshal.SizeOf - cannot be marshaled as an unmanaged structure...
1 сообщений из 1, страница 1 из 1
Структура и Marshal.SizeOf - cannot be marshaled as an unmanaged structure...
    #39475663
bnetrealm
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Приветствую.
Подскажите пожалуйста, почему я получаю сообщение выше на строке:
int tempSize = Marshal.SizeOf(typeof(TorrentInfoType));

Имею такой код, который обращается к C++ дллке, перекидывает ей структуру, чтобы та в свою очередь заполнила структуру данными:
Код: c#
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
...
        /// <summary>
        /// Represent info about particular file within a .torrent file.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct TorrentInfoType_FilesList
        {
            // Full file path within a .torrent
            [MarshalAs(UnmanagedType.LPWStr)]
            public string filepath;

            // Filename of a file within a .torrent
            [MarshalAs(UnmanagedType.LPWStr)]
            public string filename;
            
            // Filesize of a file within a .torrent
            public Int64 filesize;
        }
        
        /// <summary>
        /// Represent general information about a .torrent file.
        /// </summary>
        /// <see cref="DLL->TorrentInfo.cpp/h"/>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct TorrentInfoType
        {
            // Is torrent valid?
            [MarshalAs(UnmanagedType.U1)]
            public bool IsValid;

            // Torrent name/title.
            [MarshalAs(UnmanagedType.LPWStr)]
            public string name;

            // Torrent sha1 hash.
            [MarshalAs(UnmanagedType.LPWStr)]
            public string hash;

            // Torrent creation date
            public Int64 creationDate;

            // Torrent creator (usually, software дшлу uTorrent/3310)
            [MarshalAs(UnmanagedType.LPWStr)]
            public string creator;

            // Torrent author's comment.
            [MarshalAs(UnmanagedType.LPWStr)]
            public string comment;

            // Is torrent private?
            [MarshalAs(UnmanagedType.U1)]
            public bool IsPrivate;

            // Total number of bytes the torrent-file represents (all the files in it).
            public Int64 totalSize;

            // Files in torrent.
            public int filesCount;

            public int pieceLength;
            public int piecesCount;

            // Files list in .torrent
            [MarshalAs(UnmanagedType.LPArray)]
            public TorrentInfoType_FilesList[] files;
        }

        [DllImport(Globals.WRAPPER_DLL, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        private static extern TORRENT_ERROR dll_TorrentGetInfo(string filepath, IntPtr infoStruct);

...

        /// <summary>
        /// Retrieves .torrent information (creator, comment, files count and so on)
        /// </summary>
        /// <param name="filepath">full path to .torrent file (ex. C:\torr.torrent)</param>
        /// <returns></returns>
        public static bool GetTorrentInfo(string filepath, out TorrentInfoType info)
        {
            // Init structure with default values.
            info = new TorrentInfoType()
            {
                IsValid = false,
                name = "Unknown",
                hash = "",
                creationDate = 0,
                creator = "Unknown creator",
                comment = "",
                IsPrivate = false,
                totalSize = 0,
                filesCount = 0,
                pieceLength = 0,
                piecesCount = 0,
                files = new TorrentInfoType_FilesList[]
                {
                    
                }
            };

            // Is .torrent exists?
            if (!File.Exists(filepath))
            {
                AppCore.ShowErr(
                    String.Format(AppCore.LS("Error.FileNotExists"), filepath)
                );

                return false;
            }

            // Allocate structure to be ready marshalled in/out DLL.
            int tempSize = Marshal.SizeOf(typeof(TorrentInfoType)); <- тут ошибка.
            IntPtr pInfo = Marshal.AllocHGlobal(tempSize);
            Marshal.StructureToPtr(info, pInfo, false);

            // Query info.
            var err = dll_TorrentGetInfo(filepath, pInfo);
            if (err == TORRENT_ERROR.TE_INFO_INVALIDTORRENT)
            {
                Marshal.FreeHGlobal(pInfo);
                return false;
            }

            // Update info structure with received data.
            info = (TorrentInfoType)(Marshal.PtrToStructure(pInfo, typeof(TorrentInfoType)));
            // Free memory.
            Marshal.FreeHGlobal(pInfo);
            DumpTorrentInfoData(info);

            return true;
        }



Ошибка начала появляться после того, как я добавил ( так как появилась необходимость получить список файлов в торренте и отдать его вместе с базовыми данными, которые уже и так возвращаю нормально ) в TorrentInfoType структуру вот этот кусок (и в С++ часть соответственно тоже), выделенный жирным в тексте выше:
// Files list in .torrent
[MarshalAs(UnmanagedType.LPArray)]
public TorrentInfoType_FilesList[] files;

Без этого куска, работает нормально.
Поясните пожалуйста новичку, в чем косяк :-\

И просто для референса, на стороне С++ структуры выглядят так:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
struct TorrentInfoType_FilesList
{
    wchar_t* filepath;
    wchar_t* filename;
    long long filesize;
};

struct TorrentInfoType
{
    bool IsValid;
    wchar_t* name;
    wchar_t* hash;
    long long creationDate;
    wchar_t* creator;
    wchar_t* comment;
    bool IsPrivate;
    long long totalSize;
    int filesCount;
    int pieceLength;
    int piecesCount;

    std::vector<TorrentInfoType_FilesList> files;
};
...
Рейтинг: 0 / 0
1 сообщений из 1, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Структура и Marshal.SizeOf - cannot be marshaled as an unmanaged structure...
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]