internal StructLayoutAttribute(LayoutKind layoutKind, int pack, int size, CharSet charSet) { this._val = layoutKind; this.Pack = pack; this.Size = size; this.CharSet = charSet; }
/// <summary> /// 初始化 <see cref="Cyjb.Compilers.Lexers.CharClass"/> 类的新实例。 /// </summary> public CharClass() { CharSet defaultSet = new CharSet(); for (int i = 0; i <= char.MaxValue; i++) { defaultSet.Add((char)i); } charClassList = new List<CharSet>(); charClassList.Add(defaultSet); }
public bool IsSuperSetOf(CharSet rhs) { Contract.Requires(rhs != null); foreach (char ch in rhs.m_chars) { if (m_chars.IndexOf(ch) < 0) return false; } return true; }
public static char[,] AutoTile(char[,] data, CharSet charSet) { var width = data.GetLength(0); var height = data.GetLength(1); var tiles = new char[width, height]; for(var x = 0; x < width; ++x) { for(var y = 0; y < height; ++y) { tiles[x, y] = GetTile(data, charSet, x, y); } } return tiles; }
public static unsafe string GetText(IntPtr ptr, CharSet charSet) { switch (charSet) { case CharSet.None: case CharSet.Ansi: return Marshal.PtrToStringAnsi(((void*) ptr).pszText); case CharSet.Unicode: return Marshal.PtrToStringUni(((void*) ptr).pszText); } return Marshal.PtrToStringAuto(((void*) ptr).pszText); }
public static object DynamicDllFunctionInvoke( string dllPath, string entryPoint, MethodAttributes methodAttr, CallingConvention nativeCallConv, CharSet nativeCharSet, Type returnType, Type[] parameterTypes, object[] parameterValues ) { string dllName = Path.GetFileNameWithoutExtension(dllPath); // ����һ����̬����(assembly)��ģ��(module) AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = string.Format("A{0}{1}", dllName, Guid.NewGuid().ToString( "N" ) ); AssemblyBuilder dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule( string.Format("M{0}{1}", dllName, Guid.NewGuid().ToString("N")) ); // ʹ��ָ������Ϣ����ƽ̨����ǩ�� MethodBuilder dynamicMethod = dynamicModule.DefinePInvokeMethod( entryPoint, dllPath, methodAttr, CallingConventions.Standard, returnType, parameterTypes, nativeCallConv, nativeCharSet ); // �������� dynamicModule.CreateGlobalFunctions(); // ���ƽ̨���õķ��� MethodInfo methodInfo = dynamicModule.GetMethod(entryPoint, parameterTypes); // ���÷��йܺ�������÷��صĽ�� object result = methodInfo.Invoke(null, parameterValues); return result; }
public static string GetText(IntPtr ptr, CharSet charSet) { IntPtr ptr2 = Marshal.ReadIntPtr(ptr, Marshal.SizeOf(typeof(NMHDR))); if (ptr2 == IntPtr.Zero) { NMTTDISPINFO nmttdispinfo = (NMTTDISPINFO) Marshal.PtrToStructure(ptr, typeof(NMTTDISPINFO)); return nmttdispinfo.szText; } switch (charSet) { case CharSet.None: case CharSet.Ansi: return Marshal.PtrToStringAnsi(ptr2); case CharSet.Unicode: return Marshal.PtrToStringUni(ptr2); } return Marshal.PtrToStringAuto(ptr2); }
public static char GetTile(char[,] data, CharSet charSet, int x, int y) { if(data[x, y] == '-') { return charSet.HorizontalLine; } else if(data[x, y] == '|') { return charSet.VerticalLine; } else if(data[x, y] == ' ') { return charSet.Empty; } else { var top = GetCharAt(data, x, y - 1) != ' '; var bottom = GetCharAt(data, x, y + 1) != ' '; var left = GetCharAt(data, x - 1, y) != ' '; var right = GetCharAt(data, x + 1, y) != ' '; if(top && bottom && left && right) { return charSet.Cross; } else if(!top && bottom && left && right) { return charSet.STee; } else if(top && !bottom && left && right) { return charSet.NTee; } else if(top && bottom && !left && right) { return charSet.ETee; } else if(top && bottom && left && !right) { return charSet.WTee; } else if(!top && !bottom && left && right) { return charSet.HorizontalLine; } else if(top && bottom && !left && !right) { return charSet.VerticalLine; } else if(!top && bottom && !left && right) { return charSet.NWCorner; } else if(!top && bottom && left && !right) { return charSet.NECorner; } else if(top && !bottom && !left && right) { return charSet.SWCorner; } else if(top && !bottom && left && !right) { return charSet.SECorner; } return charSet.Pillar; } }
private static IEnumerable <MemberDeclarationSyntax> WriteFields(List <MemberDeclarationSyntax> membersToWrite, Context.SyntaxAndSymbol first, OutputWriter writer) { var fields = membersToWrite.OfType <FieldDeclarationSyntax>().ToList(); var nonFields = membersToWrite.Except(fields); // also static fields should be separately dealt with //Not needed anymore ... reflection takes care of this //if (fields.Count > 0 && fields.Any(j => j.GetModifiers().Any(SyntaxKind.ConstKeyword) || // j.GetModifiers().Any(SyntaxKind.StaticKeyword))) //{ // writer.WriteLine("enum __staticFieldTuple = __Tuple!(" + // fields.Where( // j => // j.GetModifiers().Any(SyntaxKind.ConstKeyword) || // j.GetModifiers().Any(SyntaxKind.StaticKeyword)) // .Select( // k => // "\"" + // WriteIdentifierName.TransformIdentifier( // k.Declaration.Variables[0].Identifier.ValueText) + "\"") // .Aggregate((i, j) => i + "," + j) + ");//Reflection Support"); //} var structLayout = first.Syntax.GetAttribute(Context.StructLayout); if (structLayout != null) { LayoutKind value = LayoutKind.Auto; if ( structLayout.ArgumentList.Arguments.Any( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Value")) { value = (LayoutKind) Enum.Parse(typeof(LayoutKind), structLayout.ArgumentList.Arguments.FirstOrDefault( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Value") .Expression.ToFullString() .SubstringAfterLast('.')); } else if (structLayout.ArgumentList.Arguments.Count > 0 && structLayout.ArgumentList.Arguments[0].NameEquals == null) { value = (LayoutKind) Enum.Parse(typeof(LayoutKind), structLayout.ArgumentList.Arguments[0].Expression.ToFullString() .SubstringAfterLast('.')); } int pack = -1; int size = -1; CharSet charset = CharSet.Auto; // if (structLayout.ArgumentList.Arguments.Count > 1) { try { if ( structLayout.ArgumentList.Arguments.Any( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "CharSet")) { charset = (CharSet) Enum.Parse(typeof(CharSet), structLayout.ArgumentList.Arguments.FirstOrDefault( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "CharSet") .Expression.ToFullString() .SubstringAfterLast('.')); //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value"); } //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value"); else if (structLayout.ArgumentList.Arguments.Count > 1 && structLayout.ArgumentList.Arguments[1].NameEquals == null) { charset = (CharSet) Enum.Parse(typeof(CharSet), structLayout.ArgumentList.Arguments[1].Expression.ToFullString() .SubstringAfterLast('.')); } } catch (Exception ex) { } try { if ( structLayout.ArgumentList.Arguments.Any( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Pack")) { pack = int.Parse( structLayout.ArgumentList.Arguments.FirstOrDefault( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Pack") .Expression.ToFullString()); } //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value"); else if (structLayout.ArgumentList.Arguments.Count > 2 && structLayout.ArgumentList.Arguments[2].NameEquals == null) { pack = int.Parse(structLayout.ArgumentList.Arguments[2].Expression.ToFullString()); } } catch (Exception ex) { } try { if ( structLayout.ArgumentList.Arguments.Any( k => k.NameEquals != null && k.NameEquals.Name.ToFullString().Trim() == "Size")) { size = int.Parse( structLayout.ArgumentList.Arguments.FirstOrDefault( k => k.NameColon != null && k.NameColon.ToFullString().Trim() == "Size") .Expression.ToFullString()); } //structLayout.ArgumentList.Arguments.Where (k => k.Expression is MemberAccessExpressionSyntax).FirstOrDefault(k=>(k.Expression as MemberAccessExpressionSyntax).Name.ToFullString() == "Value"); else if (structLayout.ArgumentList.Arguments.Count > 3 && structLayout.ArgumentList.Arguments[3].NameEquals == null) { size = int.Parse(structLayout.ArgumentList.Arguments[3].Expression.ToFullString()); } } catch (Exception ex) { } // size = int.Parse (structLayout.ArgumentList.Arguments [3].Expression.ToFullString ()); } // var pack = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "Pack"); // var charset = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "CharSet"); // var size = structLayout.ArgumentList.Arguments.FirstOrDefault (k => k.NameColon.Name.ToFullString() == "Size"); if (value == LayoutKind.Explicit) { var fieldGroups = fields.GroupBy(f => f.GetAttribute(Context.FieldOffset).ArgumentList.Arguments[0].ToString()) .OrderBy(k => k.Key); writer.Indent++; foreach (var group in fieldGroups) { writer.WriteLine("//FieldOffset(" + @group.Key + ")"); writer.WriteLine("union {"); foreach (var member in @group) { Core.Write(writer, member); } writer.WriteLine("}"); } // foreach (var member in fields) // { // // writer.WriteLine(); // Core.Write (writer, member); // } } else if (value == LayoutKind.Sequential) { fields = SortFields(fields); writer.Indent++; foreach (var member in fields) { if (pack != -1) { writer.WriteLine("align (" + pack + "): //Pack = " + pack); } // writer.WriteLine(); Core.Write(writer, member); } } else { //Looks like C# aligns to 1 by default ... don't know about D... fields = SortFields(fields); writer.Indent++; foreach (var member in fields) { pack = 1; //TODO: on mac osx and mono this is required, on windows, it causes and issue // writer.WriteLine("align (" + pack + "): //Pack = " + pack + " C# default"); // writer.WriteLine(); Core.Write(writer, member); } } } else { //Looks like C# aligns to 1 by default ... don't know about D... fields = SortFields(fields); writer.Indent++; foreach (var member in fields) { var pack = 1; //TODO: on mac osx and mono this is required, on windows, it causes an issue (sizes are different) // writer.WriteLine("align (" + pack + "): //Pack = " + pack + "C# default"); // writer.WriteLine(); Core.Write(writer, member); } } return(nonFields); }
public DefaultCharSetAttribute(CharSet charSet) { _set = charSet; }
/// <summary> /// Allocates a managed String and copies all characters up to the first null character or at most <paramref name="length"/> characters from a string stored in unmanaged memory into it. /// </summary> /// <param name="ptr">The address of the first character.</param> /// <param name="length">The number of characters to copy.</param> /// <param name="charSet">The character set of the string.</param> /// <returns> /// A managed string that holds a copy of the unmanaged string if the value of the <paramref name="ptr"/> parameter is not null; /// otherwise, this method returns null. /// </returns> public static string GetString(IntPtr ptr, int length, CharSet charSet = CharSet.Auto) => GetString(ptr, charSet, length * GetCharSize(charSet));
/// <summary>Writes the specified string to a pointer to allocated memory.</summary> /// <param name="value">The string value.</param> /// <param name="ptr">The pointer to the allocated memory.</param> /// <param name="byteCnt">The resulting number of bytes written.</param> /// <param name="nullTerm">if set to <c>true</c> include a null terminator at the end of the string in the count if <paramref name="value"/> does not equal <c>null</c>.</param> /// <param name="charSet">The character set of the string.</param> /// <param name="allocatedBytes">If known, the total number of bytes allocated to the native memory in <paramref name="ptr"/>.</param> public static void Write(string value, IntPtr ptr, out int byteCnt, bool nullTerm = true, CharSet charSet = CharSet.Auto, long allocatedBytes = long.MaxValue) { if (value is null) { byteCnt = 0; return; } if (ptr == IntPtr.Zero) { throw new ArgumentNullException(nameof(ptr)); } var bytes = GetBytes(value, nullTerm, charSet); if (bytes.Length > allocatedBytes) { throw new ArgumentOutOfRangeException(nameof(allocatedBytes)); } byteCnt = bytes.Length; Marshal.Copy(bytes, 0, ptr, byteCnt); }
// Constructors public DefaultCharSetAttribute(CharSet charSet) {}
public MethodBuilder DefinePInvokeMethod(String name, String dllName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder method = DefinePInvokeMethodHelper( name, dllName, name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet); return method; }
public DefaultCharSetAttribute(CharSet charSet);
[System.Security.SecurityCritical] // auto-generated internal static Attribute GetCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) { return(null); } #if !MONO MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule()); #endif string entryPoint, dllName = null; int token = method.MetadataToken; PInvokeAttributes flags = 0; #if MONO ((MonoMethod)method).GetPInvoke(out flags, out entryPoint, out dllName); #else scope.GetPInvokeMap(token, out flags, out entryPoint, out dllName); #endif CharSet charSet = CharSet.None; switch (flags & PInvokeAttributes.CharSetMask) { case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break; // Invalid: default to CharSet.None default: break; } CallingConvention callingConvention = CallingConvention.Cdecl; switch (flags & PInvokeAttributes.CallConvMask) { case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break; case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break; case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break; case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; // Invalid: default to CallingConvention.Cdecl default: break; } bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0; bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0; bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; bool preserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; return(new DllImportAttribute( dllName, entryPoint, charSet, exactSpelling, setLastError, preserveSig, callingConvention, bestFitMapping, throwOnUnmappableChar)); }
/// <summary> /// 返回指定的字符类对应的字符类索引。 /// </summary> /// <param name="charClass">要获取字符类索引的字符类。</param> /// <returns>字符类对应的字符类索引。</returns> public HashSet <int> GetCharClass(string charClass) { int cnt = charClassList.Count; HashSet <int> result = new HashSet <int>(); CharSet set = GetCharClassSet(charClass); if (set.Count == 0) { // 不包含任何字符类。 return(result); } CharSet setClone = new CharSet(set); for (int i = 0; i < cnt && set.Count > 0; i++) { CharSet cc = charClassList[i]; set.ExceptWith(cc); if (set.Count == setClone.Count) { // 当前字符类与 set 没有重叠。 continue; } // 得到当前字符类与 set 重叠的部分。 setClone.ExceptWith(set); if (setClone.Count == cc.Count) { // 完全被当前字符类包含,直接添加。 result.Add(i); if (cc.Count > 1) { // 记录新字符类,以备之后修改。 charClassRecord[i].Add(result); } } else { // 从当前的字符类中剔除被分割的部分。 cc.ExceptWith(setClone); // 更新字符类。 int newCC = charClassList.Count; result.Add(newCC); charClassList.Add(setClone); List <HashSet <int> > ccRecord = charClassRecord[i]; int ccrCnt = ccRecord.Count; // 更新旧的字符类集合。 for (int j = 0; j < ccrCnt; j++) { ccRecord[j].Add(newCC); } // 添加新的字符类集合。 List <HashSet <int> > newRecord = null; if (setClone.Count == 1) { charClassRecord.Add(null); } else { newRecord = new List <HashSet <int> >(ccRecord); newRecord.Add(result); charClassRecord.Add(newRecord); } } // 重新复制 set。 setClone = new CharSet(set); } return(result); }
/// <summary> /// HTTP文件上传 /// </summary> /// <param name="URL">HTTP上传地址</param> /// <param name="FileFullName">本地文件路径</param> /// <param name="FileName">服务器文件名</param> /// <param name="usesession">是否需要SESSION</param> /// <param name="BufferSize">缓存大小</param> /// <returns>执行结果</returns> public bool UpLoad(string URL, string FileFullName, string FileName = "", bool usesession = false, int BufferSize = 4096) { try { if (URL == null || FileFullName == null) { ErrMsg = "REF unvalid"; return(false); } else if (URL.Trim() == "" || FileFullName.Trim() == "") { ErrMsg = "REF unvalid"; return(false); } else { FileInfo fi = new FileInfo(FileFullName.Trim()); if (fi.Exists) { //时间戳 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //请求头部信息 StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("file"); sb.Append("\"; filename=\""); if (FileName.Trim() == "") { FileName = fi.Name; } sb.Append(FileName); sb.Append("\""); sb.Append("\r\n"); sb.Append("Content-Type: application/octet-stream"); sb.Append("\r\n"); sb.Append("\r\n"); string strPostHeader = sb.ToString(); byte[] postHeaderBytes; if (CharSet.Trim() != "") { postHeaderBytes = Encoding.GetEncoding(CharSet.Trim()).GetBytes(strPostHeader); } else { postHeaderBytes = Encoding.ASCII.GetBytes(strPostHeader); } myHttpWebRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL); myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } myHttpWebRequest.Method = "POST"; myHttpWebRequest.AllowWriteStreamBuffering = false; myHttpWebRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; long length = fi.Length + postHeaderBytes.Length + boundaryBytes.Length; long fileLength = fi.Length; myHttpWebRequest.ContentLength = length; byte[] buffer = new byte[BufferSize]; int dataRead = 0; using (FileStream fs = fi.OpenRead()) { try { using (Stream rs = myHttpWebRequest.GetRequestStream()) { rs.Write(postHeaderBytes, 0, postHeaderBytes.Length); do { dataRead = fs.Read(buffer, 0, BufferSize); rs.Write(buffer, 0, dataRead); }while (dataRead < BufferSize); } } catch { } finally { fs.Close(); } } myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; if (iStatCode == 200) { myHttpWebResponse.Close(); myHttpWebRequest.Abort(); return(true); } else { myHttpWebResponse.Close(); myHttpWebRequest.Abort(); ErrMsg = "HTTP ERR:" + iStatCode.ToString(); return(false); } } else { ErrMsg = "File Not Exists"; return(false); } } } catch (Exception ex) { ErrMsg = ex.Message; return(false); } }
/// <summary> /// 提交表单并返回URL上的HTML页面 /// </summary> /// <param name="URL">地址</param> /// <param name="Postdata">提交表单数据</param> /// <param name="usesession">是否需要SESSION</param> /// <returns>HTML代码</returns> public string PostHtml(string URL, String Postdata, bool usesession) { string Html = ""; try { myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL); myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; myHttpWebRequest.Method = "Post"; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } if (sendchunked) { myHttpWebRequest.SendChunked = true; myHttpWebRequest.TransferEncoding = TransferEncoding; } if (CharSet.Trim() != "") { byte[] data = Encoding.GetEncoding(CharSet.Trim()).GetBytes(Postdata); myHttpWebRequest.ContentLength = data.Length; Stream newStream = myHttpWebRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); } else { byte[] data = Encoding.ASCII.GetBytes(Postdata); myHttpWebRequest.ContentLength = data.Length; Stream newStream = myHttpWebRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); } //接收 myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; RConnType = myHttpWebResponse.ContentType; ConnCharSet = myHttpWebResponse.CharacterSet; ConnEncode = myHttpWebResponse.ContentEncoding; if (iStatCode == 200) { StreamReader reader = new StreamReader(myHttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding(ConnCharSet)); Html = reader.ReadToEnd(); reader.Close(); } else { ErrMsg = "HTTP ERR:" + iStatCode.ToString(); } myHttpWebResponse.Close(); myHttpWebRequest.Abort(); } catch (Exception ex) { ErrMsg = ex.Message; } return(Html); }
/// <summary> /// Marshals data from a managed list of objects to an unmanaged block of memory allocated by the <paramref name="memAlloc"/> method. /// </summary> /// <param name="values">The enumerated list of objects to marshal.</param> /// <param name="memAlloc"> /// The function that allocates the memory for the block of objects (typically <see cref="Marshal.AllocCoTaskMem(int)"/> or <see cref="Marshal.AllocHGlobal(int)"/>. /// </param> /// <param name="bytesAllocated">The bytes allocated by the <paramref name="memAlloc"/> method.</param> /// <param name="referencePointers"> /// if set to <see langword="true"/> the pointer will be processed by storing a reference to the value; if <see langword="false"/>, /// the pointer value will be directly inserted into the array of pointers. /// </param> /// <param name="charSet">The character set to use for strings.</param> /// <param name="prefixBytes">Number of bytes preceding the allocated objects.</param> /// <returns>Pointer to the allocated native (unmanaged) array of objects stored using the character set defined by <paramref name="charSet"/>.</returns> public static IntPtr MarshalObjectsToPtr(this IEnumerable <object> values, Func <int, IntPtr> memAlloc, out int bytesAllocated, bool referencePointers = false, CharSet charSet = CharSet.Auto, int prefixBytes = 0) { // Bail early if empty if (values is null || !values.Any()) { bytesAllocated = prefixBytes + IntPtr.Size; var ret = memAlloc(bytesAllocated); ret.FillMemory(0, bytesAllocated); return(ret); } // Write to memory stream using (var ms = new NativeMemoryStream(1024, 1024) { CharSet = charSet }) { ms.SetLength(ms.Position = prefixBytes); foreach (var o in values) { if (referencePointers) { ms.WriteReferenceObject(o); } else { ms.WriteObject(o); } } if (referencePointers) { ms.WriteReference(null); } ms.Flush(); // Copy to newly allocated memory using memAlloc bytesAllocated = (int)ms.Length; var ret = memAlloc(bytesAllocated); ms.Pointer.CopyTo(ret, bytesAllocated); return(ret); } }
/// <summary> /// Marshals data from a managed list of strings to an unmanaged block of memory allocated by the <paramref name="memAlloc"/> method. /// </summary> /// <param name="values">The enumerated list of strings to marshal.</param> /// <param name="packing">The packing type for the strings.</param> /// <param name="memAlloc"> /// The function that allocates the memory for the block of strings (typically <see cref="Marshal.AllocCoTaskMem(int)"/> or <see cref="Marshal.AllocHGlobal(int)"/>. /// </param> /// <param name="bytesAllocated">The bytes allocated by the <paramref name="memAlloc"/> method.</param> /// <param name="charSet">The character set to use for the strings.</param> /// <param name="prefixBytes">Number of bytes preceding the trailing strings.</param> /// <returns> /// Pointer to the allocated native (unmanaged) array of strings stored using the <paramref name="packing"/> model and the character /// set defined by <paramref name="charSet"/>. /// </returns> public static IntPtr MarshalToPtr(this IEnumerable <string> values, StringListPackMethod packing, Func <int, IntPtr> memAlloc, out int bytesAllocated, CharSet charSet = CharSet.Auto, int prefixBytes = 0) { // Bail early if empty if (values is null || !values.Any()) { bytesAllocated = prefixBytes + (packing == StringListPackMethod.Concatenated ? StringHelper.GetCharSize(charSet) : IntPtr.Size); var ret = memAlloc(bytesAllocated); ret.FillMemory(0, bytesAllocated); return(ret); } // Write to memory stream using (var ms = new NativeMemoryStream(1024, 1024) { CharSet = charSet }) { ms.SetLength(ms.Position = prefixBytes); if (packing == StringListPackMethod.Packed) { foreach (var s in values) { ms.WriteReference(s); } ms.WriteReference(null); } else { foreach (var s in values) { if (string.IsNullOrEmpty(s)) { throw new ArgumentException("Concatenated string arrays cannot contain empty or null strings."); } ms.Write(s); } ms.Write(""); } ms.Flush(); // Copy to newly allocated memory using memAlloc bytesAllocated = (int)ms.Length; var ret = memAlloc(bytesAllocated); ms.Pointer.CopyTo(ret, bytesAllocated); return(ret); } }
public MethodBuilder DefinePInvokeMethod ( string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { check_name ("name", name); check_name ("dllName", dllName); check_name ("entryName", entryName); if ((attributes & MethodAttributes.Abstract) != 0) throw new ArgumentException ("PInvoke methods must be static and native and cannot be abstract."); if (IsInterface) throw new ArgumentException ("PInvoke methods cannot exist on interfaces."); check_not_created (); MethodBuilder res = new MethodBuilder ( this, name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, dllName, entryName, nativeCallConv, nativeCharSet); append_method (res); return res; }
public void SetCustomAttribute (CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException ("customBuilder"); switch (customBuilder.Ctor.ReflectedType.FullName) { case "System.Runtime.CompilerServices.MethodImplAttribute": byte[] data = customBuilder.Data; int impla; // the (stupid) ctor takes a short or an int ... impla = (int)data [2]; impla |= ((int)data [3]) << 8; iattrs |= (MethodImplAttributes)impla; return; case "System.Runtime.InteropServices.DllImportAttribute": CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr (customBuilder); bool preserveSig = true; /* * It would be easier to construct a DllImportAttribute from * the custom attribute builder, but the DllImportAttribute * does not contain all the information required here, ie. * - some parameters, like BestFitMapping has three values * ("on", "off", "missing"), but DllImportAttribute only * contains two (on/off). * - PreserveSig is true by default, while it is false by * default in DllImportAttribute. */ pi_dll = (string)attr.ctorArgs[0]; if (pi_dll == null || pi_dll.Length == 0) throw new ArgumentException ("DllName cannot be empty"); native_cc = System.Runtime.InteropServices.CallingConvention.Winapi; for (int i = 0; i < attr.namedParamNames.Length; ++i) { string name = attr.namedParamNames [i]; object value = attr.namedParamValues [i]; if (name == "CallingConvention") native_cc = (CallingConvention)value; else if (name == "CharSet") charset = (CharSet)value; else if (name == "EntryPoint") pi_entry = (string)value; else if (name == "ExactSpelling") ExactSpelling = (bool)value; else if (name == "SetLastError") SetLastError = (bool)value; else if (name == "PreserveSig") preserveSig = (bool)value; else if (name == "BestFitMapping") BestFitMapping = (bool)value; else if (name == "ThrowOnUnmappableChar") ThrowOnUnmappableChar = (bool)value; } attrs |= MethodAttributes.PinvokeImpl; if (preserveSig) iattrs |= MethodImplAttributes.PreserveSig; return; case "System.Runtime.InteropServices.PreserveSigAttribute": iattrs |= MethodImplAttributes.PreserveSig; return; case "System.Runtime.CompilerServices.SpecialNameAttribute": attrs |= MethodAttributes.SpecialName; return; case "System.Security.SuppressUnmanagedCodeSecurityAttribute": attrs |= MethodAttributes.HasSecurity; break; } if (cattrs != null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; cattrs.CopyTo (new_array, 0); new_array [cattrs.Length] = customBuilder; cattrs = new_array; } else { cattrs = new CustomAttributeBuilder [1]; cattrs [0] = customBuilder; } }
/// <summary>Allocates a block of memory allocated from the unmanaged COM task allocator sufficient to hold the number of specified characters.</summary> /// <param name="count">The number of characters, inclusive of the null terminator.</param> /// <param name="charSet">The character set.</param> /// <returns>The address of the block of memory allocated.</returns> public static IntPtr AllocChars(uint count, CharSet charSet = CharSet.Auto) => AllocChars(count, Marshal.AllocCoTaskMem, charSet);
[System.Security.SecurityCritical] // auto-generated private MethodBuilder DefinePInvokeMethodHelper( String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); CheckContext(parameterTypeRequiredCustomModifiers); CheckContext(parameterTypeOptionalCustomModifiers); AppDomain.CheckDefinePInvokeSupported(); lock (SyncRoot) { return DefinePInvokeMethodHelperNoLock(name, dllName, importName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet); } }
public IEnumerable <IAttribute> GetAttributes() { var b = new AttributeListBuilder(module); var metadata = module.metadata; var typeDefinition = metadata.GetTypeDefinition(handle); // SerializableAttribute if ((typeDefinition.Attributes & TypeAttributes.Serializable) != 0) { b.Add(KnownAttribute.Serializable); } // ComImportAttribute if ((typeDefinition.Attributes & TypeAttributes.Import) != 0) { b.Add(KnownAttribute.ComImport); } #region StructLayoutAttribute LayoutKind layoutKind = LayoutKind.Auto; switch (typeDefinition.Attributes & TypeAttributes.LayoutMask) { case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; } CharSet charSet = CharSet.None; switch (typeDefinition.Attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; } var layout = typeDefinition.GetLayout(); LayoutKind defaultLayoutKind = Kind == TypeKind.Struct ? LayoutKind.Sequential : LayoutKind.Auto; if (layoutKind != defaultLayoutKind || charSet != CharSet.Ansi || layout.PackingSize > 0 || layout.Size > 0) { var structLayout = new AttributeBuilder(module, KnownAttribute.StructLayout); structLayout.AddFixedArg( new TopLevelTypeName("System.Runtime.InteropServices", "LayoutKind"), (int)layoutKind); if (charSet != CharSet.Ansi) { var charSetType = Compilation.FindType(new TopLevelTypeName("System.Runtime.InteropServices", "CharSet")); structLayout.AddNamedArg("CharSet", charSetType, (int)charSet); } if (layout.PackingSize > 0) { structLayout.AddNamedArg("Pack", KnownTypeCode.Int32, (int)layout.PackingSize); } if (layout.Size > 0) { structLayout.AddNamedArg("Size", KnownTypeCode.Int32, (int)layout.Size); } b.Add(structLayout.Build()); } #endregion b.Add(typeDefinition.GetCustomAttributes(), SymbolKind.TypeDefinition); b.AddSecurityAttributes(typeDefinition.GetDeclarativeSecurityAttributes()); return(b.Build()); }
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder mb = DefineMethod(name, attributes | MethodAttributes.PinvokeImpl, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); mb.SetDllImportPseudoCustomAttribute(dllName, entryName, nativeCallConv, nativeCharSet, null, null, null, null, null); return mb; }
private static unsafe IntPtr GetProcAddress(IntPtr hModule, byte *methodName, CharSet charSetMangling) { // First look for the unmangled name. If it is unicode function, we are going // to need to check for the 'W' API because it takes precedence over the // unmangled one (on NT some APIs have unmangled ANSI exports). var exactMatch = Interop.mincore.GetProcAddress(hModule, methodName); if ((charSetMangling == CharSet.Ansi && exactMatch != IntPtr.Zero) || charSetMangling == 0) { return(exactMatch); } int nameLength = string.strlen(methodName); // We need to add an extra byte for the suffix, and an extra byte for the null terminator byte *probedMethodName = stackalloc byte[nameLength + 2]; for (int i = 0; i < nameLength; i++) { probedMethodName[i] = methodName[i]; } probedMethodName[nameLength + 1] = 0; probedMethodName[nameLength] = (charSetMangling == CharSet.Ansi) ? (byte)'A' : (byte)'W'; IntPtr probedMethod = Interop.mincore.GetProcAddress(hModule, probedMethodName); if (probedMethod != IntPtr.Zero) { return(probedMethod); } return(exactMatch); }
[System.Security.SecurityCritical] // auto-generated #endif public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { Contract.Ensures(Contract.Result<MethodBuilder>() != null); lock(SyncRoot) { return DefinePInvokeMethodNoLock(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } }
private string MakeDllImport( CallingConvention? cc = null, CharSet? charSet = null, bool? exactSpelling = null, bool? preserveSig = null, bool? setLastError = null, bool? bestFitMapping = null, bool? throwOnUnmappableChar = null) { StringBuilder sb = new StringBuilder("[DllImport(\"bar\""); if (cc != null) { sb.Append(", CallingConvention = CallingConvention."); sb.Append(cc.Value); } if (charSet != null) { sb.Append(", CharSet = CharSet."); sb.Append(charSet.Value); } if (exactSpelling != null) { sb.Append(", ExactSpelling = "); sb.Append(exactSpelling.Value ? "true" : "false"); } if (preserveSig != null) { sb.Append(", PreserveSig = "); sb.Append(preserveSig.Value ? "true" : "false"); } if (setLastError != null) { sb.Append(", SetLastError = "); sb.Append(setLastError.Value ? "true" : "false"); } if (bestFitMapping != null) { sb.Append(", BestFitMapping = "); sb.Append(bestFitMapping.Value ? "true" : "false"); } if (throwOnUnmappableChar != null) { sb.Append(", ThrowOnUnmappableChar = "); sb.Append(throwOnUnmappableChar.Value ? "true" : "false"); } sb.Append(")]"); return sb.ToString(); }
/// <summary> /// Configures the Unicode CharSet /// </summary> public virtual MySqlDbContextOptionsBuilder UnicodeCharSet(CharSet charSet) => WithOption(e => e.WithUnicodeCharSetInfo(new CharSetInfo(charSet)));
public DefaultCharSetAttribute(CharSet charSet) { _CharSet = charSet; }
internal MethodBuilder(TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type?returnType, Type[]?returnModReq, Type[]?returnModOpt, Type[]?parameterTypes, Type[][]?paramModReq, Type[][]?paramModOpt, string dllName, string entryName, CallingConvention nativeCConv, CharSet nativeCharset) : this(tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) { pi_dll = dllName; pi_entry = entryName; native_cc = nativeCConv; charset = nativeCharset; }
internal StructLayoutAttribute(LayoutKind layoutKind, int pack, int size, CharSet charSet) { _val = layoutKind; Pack = pack; Size = size; CharSet = charSet; }
public IEnumerable <IAttribute> GetAttributes() { var b = new AttributeListBuilder(module); var metadata = module.metadata; var def = metadata.GetMethodDefinition(handle); MethodImplAttributes implAttributes = def.ImplAttributes & ~MethodImplAttributes.CodeTypeMask; #region DllImportAttribute var info = def.GetImport(); if ((attributes & MethodAttributes.PinvokeImpl) == MethodAttributes.PinvokeImpl && !info.Module.IsNil) { var dllImport = new AttributeBuilder(module, KnownAttribute.DllImport); dllImport.AddFixedArg(KnownTypeCode.String, metadata.GetString(metadata.GetModuleReference(info.Module).Name)); var importAttrs = info.Attributes; if ((importAttrs & MethodImportAttributes.BestFitMappingDisable) == MethodImportAttributes.BestFitMappingDisable) { dllImport.AddNamedArg("BestFitMapping", KnownTypeCode.Boolean, false); } if ((importAttrs & MethodImportAttributes.BestFitMappingEnable) == MethodImportAttributes.BestFitMappingEnable) { dllImport.AddNamedArg("BestFitMapping", KnownTypeCode.Boolean, true); } CallingConvention callingConvention; switch (info.Attributes & MethodImportAttributes.CallingConventionMask) { case 0: Debug.WriteLine($"P/Invoke calling convention not set on: {this}"); callingConvention = 0; break; case MethodImportAttributes.CallingConventionCDecl: callingConvention = CallingConvention.Cdecl; break; case MethodImportAttributes.CallingConventionFastCall: callingConvention = CallingConvention.FastCall; break; case MethodImportAttributes.CallingConventionStdCall: callingConvention = CallingConvention.StdCall; break; case MethodImportAttributes.CallingConventionThisCall: callingConvention = CallingConvention.ThisCall; break; case MethodImportAttributes.CallingConventionWinApi: callingConvention = CallingConvention.Winapi; break; default: throw new NotSupportedException("unknown calling convention"); } if (callingConvention != CallingConvention.Winapi) { var callingConventionType = FindInteropType(nameof(CallingConvention)); dllImport.AddNamedArg("CallingConvention", callingConventionType, (int)callingConvention); } CharSet charSet = CharSet.None; switch (info.Attributes & MethodImportAttributes.CharSetMask) { case MethodImportAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case MethodImportAttributes.CharSetAuto: charSet = CharSet.Auto; break; case MethodImportAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; } if (charSet != CharSet.None) { var charSetType = FindInteropType(nameof(CharSet)); dllImport.AddNamedArg("CharSet", charSetType, (int)charSet); } if (!info.Name.IsNil && info.Name != def.Name) { dllImport.AddNamedArg("EntryPoint", KnownTypeCode.String, metadata.GetString(info.Name)); } if ((info.Attributes & MethodImportAttributes.ExactSpelling) == MethodImportAttributes.ExactSpelling) { dllImport.AddNamedArg("ExactSpelling", KnownTypeCode.Boolean, true); } if ((implAttributes & MethodImplAttributes.PreserveSig) == MethodImplAttributes.PreserveSig) { implAttributes &= ~MethodImplAttributes.PreserveSig; } else { dllImport.AddNamedArg("PreserveSig", KnownTypeCode.Boolean, true); } if ((info.Attributes & MethodImportAttributes.SetLastError) == MethodImportAttributes.SetLastError) { dllImport.AddNamedArg("SetLastError", KnownTypeCode.Boolean, true); } if ((info.Attributes & MethodImportAttributes.ThrowOnUnmappableCharDisable) == MethodImportAttributes.ThrowOnUnmappableCharDisable) { dllImport.AddNamedArg("ThrowOnUnmappableChar", KnownTypeCode.Boolean, false); } if ((info.Attributes & MethodImportAttributes.ThrowOnUnmappableCharEnable) == MethodImportAttributes.ThrowOnUnmappableCharEnable) { dllImport.AddNamedArg("ThrowOnUnmappableChar", KnownTypeCode.Boolean, true); } b.Add(dllImport.Build()); } #endregion #region PreserveSigAttribute if (implAttributes == MethodImplAttributes.PreserveSig) { b.Add(KnownAttribute.PreserveSig); implAttributes = 0; } #endregion #region MethodImplAttribute if (implAttributes != 0) { b.Add(KnownAttribute.MethodImpl, new TopLevelTypeName("System.Runtime.CompilerServices", nameof(MethodImplOptions)), (int)implAttributes ); } #endregion b.Add(def.GetCustomAttributes()); b.AddSecurityAttributes(def.GetDeclarativeSecurityAttributes()); return(b.Build()); }
/// <summary>Copies the contents of a managed <see cref="SecureString"/> object to a block of memory allocated from a supplied allocation method.</summary> /// <param name="s">The managed object to copy.</param> /// <param name="charSet">The character set.</param> /// <param name="memAllocator">The method used to allocate the memory.</param> /// <returns>The address, in unmanaged memory, where the <paramref name="s"/> parameter was copied to, or 0 if a null object was supplied.</returns> public static IntPtr AllocSecureString(SecureString s, CharSet charSet, Func <int, IntPtr> memAllocator) => AllocSecureString(s, charSet, memAllocator, out _);
/// <summary> /// It is called very early therefore can resolve only predefined attributes /// </summary> void ResolveGlobalAttributes () { if (OptAttributes == null) return; if (!OptAttributes.CheckTargets ()) return; // FIXME: Define is wrong as the type may not exist yet var DefaultCharSet_attr = new PredefinedAttribute (this, "System.Runtime.InteropServices", "DefaultCharSetAttribute"); DefaultCharSet_attr.Define (); Attribute a = ResolveModuleAttribute (DefaultCharSet_attr); if (a != null) { has_default_charset = true; DefaultCharSet = a.GetCharSetValue (); switch (DefaultCharSet) { case CharSet.Ansi: case CharSet.None: break; case CharSet.Auto: DefaultCharSetType = TypeAttributes.AutoClass; break; case CharSet.Unicode: DefaultCharSetType = TypeAttributes.UnicodeClass; break; default: Report.Error (1724, a.Location, "Value specified for the argument to `{0}' is not valid", DefaultCharSet_attr.GetSignatureForError ()); break; } } }
internal static MethodImportAttributes MakeFlags(bool exactSpelling, CharSet charSet, bool setLastError, CallingConvention callingConvention, bool?useBestFit, bool?throwOnUnmappable) { MethodImportAttributes result = 0; if (exactSpelling) { result |= MethodImportAttributes.ExactSpelling; } switch (charSet) { case CharSet.Ansi: result |= MethodImportAttributes.CharSetAnsi; break; case CharSet.Unicode: result |= MethodImportAttributes.CharSetUnicode; break; case Cci.Constants.CharSet_Auto: result |= MethodImportAttributes.CharSetAuto; break; // Dev10: use default without reporting an error } if (setLastError) { result |= MethodImportAttributes.SetLastError; } switch (callingConvention) { default: // Dev10: uses default without reporting an error result |= MethodImportAttributes.CallingConventionWinApi; break; case CallingConvention.Cdecl: result |= MethodImportAttributes.CallingConventionCDecl; break; case CallingConvention.StdCall: result |= MethodImportAttributes.CallingConventionStdCall; break; case CallingConvention.ThisCall: result |= MethodImportAttributes.CallingConventionThisCall; break; case Cci.Constants.CallingConvention_FastCall: result |= MethodImportAttributes.CallingConventionFastCall; break; } if (throwOnUnmappable.HasValue) { if (throwOnUnmappable.Value) { result |= MethodImportAttributes.ThrowOnUnmappableCharEnable; } else { result |= MethodImportAttributes.ThrowOnUnmappableCharDisable; } } if (useBestFit.HasValue) { if (useBestFit.Value) { result |= MethodImportAttributes.BestFitMappingEnable; } else { result |= MethodImportAttributes.BestFitMappingDisable; } } return(result); }
public MethodBuilder DefinePInvokeMethod (string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { if (name == null) throw new ArgumentNullException ("name"); if ((attributes & MethodAttributes.Static) == 0) throw new ArgumentException ("global methods must be static"); if (global_type_created != null) throw new InvalidOperationException ("global methods already created"); CreateGlobalType (); MethodBuilder mb = global_type.DefinePInvokeMethod (name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); addGlobalMethod (mb); return mb; }
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type?returnType, Type[]?parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException("global methods must be static"); } if (global_type_created != null) { throw new InvalidOperationException("global methods already created"); } CreateGlobalType(); MethodBuilder mb = global_type !.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); addGlobalMethod(mb); return(mb); }
internal DllImportAttribute( string dllName, string entryPoint, CharSet charSet, bool exactSpelling, bool setLastError, bool preserveSig, CallingConvention callingConvention, bool bestFitMapping, bool throwOnUnmappableChar) { _val = dllName; EntryPoint = entryPoint; CharSet = charSet; ExactSpelling = exactSpelling; SetLastError = setLastError; PreserveSig = preserveSig; CallingConvention = callingConvention; BestFitMapping = bestFitMapping; ThrowOnUnmappableChar = throwOnUnmappableChar; }
/// <summary>Gets the size of a character defined by the supplied <see cref="CharSet"/>.</summary> /// <param name="charSet">The character set to size.</param> /// <returns>The size of a standard character, in bytes, from <paramref name="charSet"/>.</returns> public static int GetCharSize(CharSet charSet = CharSet.Auto) => charSet == CharSet.Auto ? Marshal.SystemDefaultCharSize : (charSet == CharSet.Unicode ? 2 : 1);
internal void SetDllImportPseudoCustomAttribute(string dllName, string entryName, CallingConvention? nativeCallConv, CharSet? nativeCharSet, bool? bestFitMapping, bool? throwOnUnmappableChar, bool? setLastError, bool? preserveSig, bool? exactSpelling) { const short NoMangle = 0x0001; const short CharSetMask = 0x0006; const short CharSetNotSpec = 0x0000; const short CharSetAnsi = 0x0002; const short CharSetUnicode = 0x0004; const short CharSetAuto = 0x0006; const short SupportsLastError = 0x0040; const short CallConvMask = 0x0700; const short CallConvWinapi = 0x0100; const short CallConvCdecl = 0x0200; const short CallConvStdcall = 0x0300; const short CallConvThiscall = 0x0400; const short CallConvFastcall = 0x0500; // non-standard flags const short BestFitOn = 0x0010; const short BestFitOff = 0x0020; const short CharMapErrorOn = 0x1000; const short CharMapErrorOff = 0x2000; short flags = CharSetNotSpec | CallConvWinapi; if (bestFitMapping.HasValue) { flags |= bestFitMapping.Value ? BestFitOn : BestFitOff; } if (throwOnUnmappableChar.HasValue) { flags |= throwOnUnmappableChar.Value ? CharMapErrorOn : CharMapErrorOff; } if (nativeCallConv.HasValue) { flags &= ~CallConvMask; switch (nativeCallConv.Value) { case System.Runtime.InteropServices.CallingConvention.Cdecl: flags |= CallConvCdecl; break; case System.Runtime.InteropServices.CallingConvention.FastCall: flags |= CallConvFastcall; break; case System.Runtime.InteropServices.CallingConvention.StdCall: flags |= CallConvStdcall; break; case System.Runtime.InteropServices.CallingConvention.ThisCall: flags |= CallConvThiscall; break; case System.Runtime.InteropServices.CallingConvention.Winapi: flags |= CallConvWinapi; break; } } if (nativeCharSet.HasValue) { flags &= ~CharSetMask; switch (nativeCharSet.Value) { case CharSet.Ansi: case CharSet.None: flags |= CharSetAnsi; break; case CharSet.Auto: flags |= CharSetAuto; break; case CharSet.Unicode: flags |= CharSetUnicode; break; } } if (exactSpelling.HasValue && exactSpelling.Value) { flags |= NoMangle; } if (!preserveSig.HasValue || preserveSig.Value) { implFlags |= MethodImplAttributes.PreserveSig; } if (setLastError.HasValue && setLastError.Value) { flags |= SupportsLastError; } ImplMapTable.Record rec = new ImplMapTable.Record(); rec.MappingFlags = flags; rec.MemberForwarded = pseudoToken; rec.ImportName = this.ModuleBuilder.Strings.Add(entryName ?? name); rec.ImportScope = this.ModuleBuilder.ModuleRef.FindOrAddRecord(dllName == null ? 0 : this.ModuleBuilder.Strings.Add(dllName)); this.ModuleBuilder.ImplMap.AddRecord(rec); }
/// <summary> /// Allocates a managed String and copies all characters up to the first null character or at most <paramref name="length"/> characters from a string stored in unmanaged memory into it. /// </summary> /// <param name="ptr">The address of the first character.</param> /// <param name="length">The number of characters to copy.</param> /// <param name="charSet">The character set of the string.</param> /// <returns> /// A managed string that holds a copy of the unmanaged string if the value of the <paramref name="ptr"/> parameter is not null; /// otherwise, this method returns null. /// </returns> public static string GetString(IntPtr ptr, int length, CharSet charSet = CharSet.Auto) => IsValue(ptr) ? null : (charSet == CharSet.Auto ? Marshal.PtrToStringAuto(ptr, length) : (charSet == CharSet.Unicode ? Marshal.PtrToStringUni(ptr, length) : Marshal.PtrToStringAnsi(ptr, length)));
internal MethodBuilder (TypeBuilder tb, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnModReq, Type[] returnModOpt, Type[] parameterTypes, Type[][] paramModReq, Type[][] paramModOpt, String dllName, String entryName, CallingConvention nativeCConv, CharSet nativeCharset) : this (tb, name, attributes, callingConvention, returnType, returnModReq, returnModOpt, parameterTypes, paramModReq, paramModOpt) { pi_dll = dllName; pi_entry = entryName; native_cc = nativeCConv; charset = nativeCharset; }
/// <summary>Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator.</summary> /// <param name="s">A managed string to be copied.</param> /// <param name="charSet">The character set.</param> /// <returns>The allocated memory block, or 0 if <paramref name="s"/> is null.</returns> public static IntPtr AllocString(string s, CharSet charSet = CharSet.Auto) => charSet == CharSet.Auto ? Marshal.StringToCoTaskMemAuto(s) : (charSet == CharSet.Unicode ? Marshal.StringToCoTaskMemUni(s) : Marshal.StringToCoTaskMemAnsi(s));
internal static Cci.PInvokeAttributes MakeFlags(bool noMangle, CharSet charSet, bool setLastError, CallingConvention callingConvention, bool? useBestFit, bool? throwOnUnmappable) { Cci.PInvokeAttributes result = 0; if (noMangle) { result |= Cci.PInvokeAttributes.NoMangle; } switch (charSet) { default: // Dev10: use default without reporting an error case Cci.Constants.CharSet_None: break; case CharSet.Ansi: result |= Cci.PInvokeAttributes.CharSetAnsi; break; case CharSet.Unicode: result |= Cci.PInvokeAttributes.CharSetUnicode; break; case Cci.Constants.CharSet_Auto: result |= Cci.PInvokeAttributes.CharSetAuto; break; } if (setLastError) { result |= Cci.PInvokeAttributes.SupportsLastError; } switch (callingConvention) { default: // Dev10: uses default without reporting an error case CallingConvention.Winapi: result |= Cci.PInvokeAttributes.CallConvWinapi; break; case CallingConvention.Cdecl: result |= Cci.PInvokeAttributes.CallConvCdecl; break; case CallingConvention.StdCall: result |= Cci.PInvokeAttributes.CallConvStdcall; break; case CallingConvention.ThisCall: result |= Cci.PInvokeAttributes.CallConvThiscall; break; case Cci.Constants.CallingConvention_FastCall: result |= Cci.PInvokeAttributes.CallConvFastcall; break; } if (throwOnUnmappable.HasValue) { if (throwOnUnmappable.Value) { result |= Cci.PInvokeAttributes.ThrowOnUnmappableCharEnabled; } else { result |= Cci.PInvokeAttributes.ThrowOnUnmappableCharDisabled; } } if (useBestFit.HasValue) { if (useBestFit.Value) { result |= Cci.PInvokeAttributes.BestFitEnabled; } else { result |= Cci.PInvokeAttributes.BestFitDisabled; } } return result; }
public IServiceProvider CreateContextServices(CharSetBehavior charSetBehavior, CharSet charSet) => ((IInfrastructure <IServiceProvider>) new DbContext(CreateOptions(charSetBehavior, charSet))).Instance;
public MethodBuilder DefinePInvokeMethod(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder method = DefinePInvokeMethodHelper( name, dllName, entryName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet); return method; }
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return(DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet)); }
[System.Security.SecurityCritical] // auto-generated private MethodBuilder DefinePInvokeMethodHelperNoLock( String name, String dllName, String importName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); if (dllName == null) throw new ArgumentNullException("dllName"); if (dllName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "dllName"); if (importName == null) throw new ArgumentNullException("importName"); if (importName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "importName"); if ((attributes & MethodAttributes.Abstract) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeMethod")); Contract.EndContractBlock(); if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) throw new ArgumentException(Environment.GetResourceString("Argument_BadPInvokeOnInterface")); ThrowIfCreated(); attributes = attributes | MethodAttributes.PinvokeImpl; MethodBuilder method = new MethodBuilder(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, m_module, this, false); //The signature grabbing code has to be up here or the signature won't be finished //and our equals check won't work. int sigLength; byte[] sigBytes = method.GetMethodSignature().InternalGetSignature(out sigLength); if (m_listMethods.Contains(method)) { throw new ArgumentException(Environment.GetResourceString("Argument_MethodRedefined")); } m_listMethods.Add(method); MethodToken token = method.GetToken(); int linkFlags = 0; switch(nativeCallConv) { case CallingConvention.Winapi: linkFlags =(int)PInvokeMap.CallConvWinapi; break; case CallingConvention.Cdecl: linkFlags =(int)PInvokeMap.CallConvCdecl; break; case CallingConvention.StdCall: linkFlags =(int)PInvokeMap.CallConvStdcall; break; case CallingConvention.ThisCall: linkFlags =(int)PInvokeMap.CallConvThiscall; break; case CallingConvention.FastCall: linkFlags =(int)PInvokeMap.CallConvFastcall; break; } switch(nativeCharSet) { case CharSet.None: linkFlags |=(int)PInvokeMap.CharSetNotSpec; break; case CharSet.Ansi: linkFlags |=(int)PInvokeMap.CharSetAnsi; break; case CharSet.Unicode: linkFlags |=(int)PInvokeMap.CharSetUnicode; break; case CharSet.Auto: linkFlags |=(int)PInvokeMap.CharSetAuto; break; } SetPInvokeData(m_module.GetNativeHandle(), dllName, importName, token.Token, linkFlags); method.SetToken(token); return method; }
public Transition(TState from, TState to, CharSet validInput = null) { ValidInput = validInput ?? new CharSet(); From = from; To = to; }
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet); }
public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } switch (customBuilder.Ctor.ReflectedType.FullName) { case "System.Runtime.CompilerServices.MethodImplAttribute": byte[] data = customBuilder.Data; int impla; // the (stupid) ctor takes a short or an int ... impla = (int)data [2]; impla |= ((int)data [3]) << 8; iattrs |= (MethodImplAttributes)impla; return; case "System.Runtime.InteropServices.DllImportAttribute": CustomAttributeBuilder.CustomAttributeInfo attr = CustomAttributeBuilder.decode_cattr(customBuilder); bool preserveSig = true; /* * It would be easier to construct a DllImportAttribute from * the custom attribute builder, but the DllImportAttribute * does not contain all the information required here, ie. * - some parameters, like BestFitMapping has three values * ("on", "off", "missing"), but DllImportAttribute only * contains two (on/off). * - PreserveSig is true by default, while it is false by * default in DllImportAttribute. */ pi_dll = (string)attr.ctorArgs[0]; if (pi_dll == null || pi_dll.Length == 0) { throw new ArgumentException("DllName cannot be empty"); } native_cc = System.Runtime.InteropServices.CallingConvention.Winapi; for (int i = 0; i < attr.namedParamNames.Length; ++i) { string name = attr.namedParamNames [i]; object value = attr.namedParamValues [i]; if (name == "CallingConvention") { native_cc = (CallingConvention)value; } else if (name == "CharSet") { charset = (CharSet)value; } else if (name == "EntryPoint") { pi_entry = (string)value; } else if (name == "ExactSpelling") { ExactSpelling = (bool)value; } else if (name == "SetLastError") { SetLastError = (bool)value; } else if (name == "PreserveSig") { preserveSig = (bool)value; } #if NET_1_1 else if (name == "BestFitMapping") { BestFitMapping = (bool)value; } else if (name == "ThrowOnUnmappableChar") { ThrowOnUnmappableChar = (bool)value; } #endif } attrs |= MethodAttributes.PinvokeImpl; if (preserveSig) { iattrs |= MethodImplAttributes.PreserveSig; } return; case "System.Runtime.InteropServices.PreserveSigAttribute": iattrs |= MethodImplAttributes.PreserveSig; return; #if NET_2_0 case "System.Runtime.CompilerServices.SpecialNameAttribute": attrs |= MethodAttributes.SpecialName; return; #endif case "System.Security.SuppressUnmanagedCodeSecurityAttribute": attrs |= MethodAttributes.HasSecurity; break; } if (cattrs != null) { CustomAttributeBuilder[] new_array = new CustomAttributeBuilder [cattrs.Length + 1]; cattrs.CopyTo(new_array, 0); new_array [cattrs.Length] = customBuilder; cattrs = new_array; } else { cattrs = new CustomAttributeBuilder [1]; cattrs [0] = customBuilder; } }
/// <summary> /// 获取字符类中包含的所有字符。 /// </summary> /// <param name="charClass">要获取所有字符的字符类。</param> /// <returns>字符类中包含的所有字符。</returns> private static CharSet GetCharClassSet(string charClass) { CharSet set = new CharSet(); if (RegexCharClass.IsSubtraction(charClass) || RegexCharClass.ContainsCategory(charClass)) { for (int i = 0; i <= char.MaxValue; i++) { if (RegexCharClass.CharInClass((char)i, charClass)) { set.Add((char)i); } } } else { // 如果不包含差集和 Unicode 字符分类的话,可以更快。 string ranges = RegexCharClass.GetCharClassRanges(charClass); if (RegexCharClass.IsNegated(charClass)) { int s = 0; for (int i = 0; i < ranges.Length; i++) { for (int j = s; j < ranges[i]; j++) { set.Add((char)j); } i++; s = i < ranges.Length ? ranges[i] : char.MaxValue + 1; } for (int j = s; j <= char.MaxValue; j++) { set.Add((char)j); } } else { for (int i = 0; i < ranges.Length; i++) { int j = ranges[i++]; int end = i < ranges.Length ? ranges[i] : char.MaxValue + 1; for (; j < end; j++) { set.Add((char)j); } } } } return set; }
internal virtual bool IsCharSetSupported(string charset) { return(CharSet?.Equals(charset, StringComparison.OrdinalIgnoreCase) ?? false); }
/// <summary> /// 返回指定的字符类对应的字符类索引。 /// </summary> /// <param name="charClass">要获取字符类索引的字符类。</param> /// <returns>字符类对应的字符类索引。</returns> public HashSet<int> GetCharClass(string charClass) { int cnt = charClassList.Count; HashSet<int> result = new HashSet<int>(); CharSet set = GetCharClassSet(charClass); if (set.Count == 0) { // 不包含任何字符类。 return result; } CharSet setClone = new CharSet(set); for (int i = 0; i < cnt && set.Count > 0; i++) { CharSet cc = charClassList[i]; set.ExceptWith(cc); if (set.Count == setClone.Count) { // 当前字符类与 set 没有重叠。 continue; } // 得到当前字符类与 set 重叠的部分。 setClone.ExceptWith(set); if (setClone.Count == cc.Count) { // 完全被当前字符类包含,直接添加。 result.Add(i); if (cc.Count > 1) { // 记录新字符类,以备之后修改。 charClassRecord[i].Add(result); } } else { // 从当前的字符类中剔除被分割的部分。 cc.ExceptWith(setClone); // 更新字符类。 int newCC = charClassList.Count; result.Add(newCC); charClassList.Add(setClone); List<HashSet<int>> ccRecord = charClassRecord[i]; int ccrCnt = ccRecord.Count; // 更新旧的字符类集合。 for (int j = 0; j < ccrCnt; j++) { ccRecord[j].Add(newCC); } // 添加新的字符类集合。 List<HashSet<int>> newRecord = null; if (setClone.Count == 1) { charClassRecord.Add(null); } else { newRecord = new List<HashSet<int>>(ccRecord); newRecord.Add(result); charClassRecord.Add(newRecord); } } // 重新复制 set。 setClone = new CharSet(set); } return result; }
protected virtual void Generate(Action <ModelBuilder> buildAction, CharSetBehavior charSetBehavior, CharSet charSet, params MigrationOperation[] operations) { var services = MySqlTestHelpers.Instance.CreateContextServices(charSetBehavior, charSet); var modelBuilder = MySqlTestHelpers.Instance.CreateConventionBuilder(services); buildAction(modelBuilder); var batch = services.GetRequiredService <IMigrationsSqlGenerator>() .Generate(ResetSchema(operations), modelBuilder.Model); Sql = string.Join( EOL, batch.Select(b => b.CommandText)); }
[System.Security.SecurityCritical] // auto-generated #endif private MethodBuilder DefinePInvokeMethodNoLock(String name, String dllName, String entryName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { //Global methods must be static. if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic")); } Contract.Ensures(Contract.Result<MethodBuilder>() != null); Contract.EndContractBlock(); CheckContext(returnType); CheckContext(parameterTypes); m_moduleData.m_fHasGlobal = true; return m_moduleData.m_globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); }
public AllParser(CharSet significantChars, int max = int.MaxValue) { SignificantChars = significantChars; Max = max; }