两种方式:
eval() 将字符串str当成有效的表达式来求值并返回计算结果。
exec() 跑多条语句,没有返回值

因此为了安全起见,要提供一个字典以充当命名空间。

命名空间:可以视为一个放置变量的地方。当你执行语句x=1时,将在当前命名空间存储键x和值1。当前命名空间通常是全局命名空间,但也并非必然如此。

安全问题

使用 ast.literal_eval
ast.parse
compile
dbm.dumb.open

命名空间

var = "This is a string"
varName = 'var'
s= locals()[varName]
s
'This is a string'
s2=vars()[varName]
s2
'This is a string'
s3=eval(varName)
s3
'This is a string'

locals是python的内置函数,他可以以字典的方式去访问局部和全局变量。
globals返回的是当前模块的全局变量 locals返回的是局部变量。注意,locals返回的是当前所在最小命名空间的局部变量的一个拷贝。

python里面用名字空间记录着变量

每个模块,每个函数都有自己的名字空间,记录着变量,常量,类的命名和值。
当python在使用变量时,会按照下面的步骤去搜索:

函数或类的局部变量。
全局变量。
内置变量。

for key in locals().keys():
print (key)

for value in locals().values():
print (value)

compile

Compile source into a code object that can be executed by exec() or eval().

exec()

from math import sqrt
scope={}
exec('sqrt=1',scope)
sqrt(4)
>>2.0
scope['sqrt']
>>1

eval()

unmanaged exception

?? 这个文件在哪里设置,还没找到,后面有需要了在处理

在托管程序的.config文件里,启用legacyCorruptedStateExceptionsPolicy这个属性,即简化的.config文件类似下面的文件:

<?xml version="1.0"?>
<configuration>
 <startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
 </startup>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true" />
</runtime>
</configuration>

在需要捕捉破坏性异常的函数外面加一个HandleProcessCorruptedStateExceptions属性,这个属性只控制一个函数,对托管程序的其他函数没有影响

[HandleProcessCorruptedStateExceptions]
void function()
{
try
{
}
catch (Exception e)
{
}finally
{
// 关闭数据库
if (cn.State == ConnectionState.Open)
{
cn.Close();
}
cn.Dispose();
cmd.Dispose();
transaction.Dispose();
}
}

比较返回值

 try
{
mmf = MemoryMappedFile.CreateNew("fireworksShareMemory", mmf_size);

taskPythonPlugin = new Task(() =>
{
Console.WriteLine("task python plugin start...");
task_pyton_plugin();
});

taskPythonPlugin.Start();

while (FLAG_PYTHON_LISTENING !=( flag & FLAG_PYTHON_LISTENING ))
{
Thread.Sleep(100);
}

}
catch (System.IO.IOException ex)
{
if ((uint)ex.HResult == 0x800700b7)
{
// 文件已存在,需要关闭之前未推出的进程。
Console.WriteLine("init mmf failed. " + ex.Message);
}

Console.WriteLine("init mmf failed. " + ex.Message);
Log.Error("init mmf failed. " + ex.Message);
}

Task and Thread

Task的背后的实现也是使用了线程池线程,但它的性能优于ThreadPoll,因为它使用的不是线程池的全局队列,而是使用的本地队列,使线程之间的资源竞争减少。同时Task提供了丰富的API来管理线程、控制。但是相对前面的两种耗内存,Task依赖于CPU对于多核的CPU性能远超前两者,单核的CPU三者的性能没什么差别。

Task.Run 和 Task.Factory.StartNew 里面有异常的时候都是不会抛出来的,需要在内部捕获

WaitAll is a blocking call
WhenAll - not - code will continue executing

Task

private Task taskPythonPlugin;

taskPythonPlugin = new Task(() =>
{
Console.WriteLine("task start");
task_pyton_plugin();
});

taskPythonPlugin.Start();

public void task_pyton_plugin()
{
}
阅读全文 »

[StructLayout(LayoutKind.Sequential)]
struct nng_listener
{
public UInt32 id;
}

msdn

You can use the out keyword in two contexts:

  • As a parameter modifier, which lets you pass an argument to a method by reference rather than by value.
  • In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant.

C++/CLI

貌似这个方法不推荐

WARNING
Other methods to create a .NET binding to a C# library exist. A notorious one is based on the compilation of the C++ library with the C++/CLI compiler. To keep things compatible with the Apple macOS, and because the IJW (it just works) technology sometimes does not, we suggest the use of PInvoke.

Platform Invoke (PInvoke)

allows .NET code to call functions that are implemented in a C/C++ DLL (Windows) or dylib (macOS).

pinvoke
P/Invoke Tutorial: Basics
Interop with Native Libraries

在 .NET 程序中使用 Win32 函数并不如 C++ 中方便。因为 C# 中不能引入 C++ 中常用的头文件,于是各种方法签名、结构体定义等等都需要各种寻找。然而 PInvoke.net 帮助我们解决了这个问题。本文推荐一款 Visual Studio 插件来帮助我们更快速地插入 Win32 函数签名。

在 Visual Studio 的“工具->扩展和更新”里面在线下载安装插件

参数类型

结构体指针

typedef struct nng_socket_s {
uint32_t id;
} nng_socket;

NNG_DECL int nng_pair0_open(nng_socket *);
[StructLayout(LayoutKind.Sequential)]
public struct nng_socket
{
public UInt32 id;
}

[DllImport(Import.nngLib, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
static extern int nng_pair0_open(ref nng_socket socket);

const char *

NNG_DECL int nng_listen(nng_socket, const char *, nng_listener *, int);
[DllImport(Import.nngLib, SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern int nng_listen(nng_socket socket, [MarshalAs(UnmanagedType.LPStr)] string url, nng_listener listener, int flag);

// 中文需要使用 CharSet.Unicode
[DllImport(Import.nngLib, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
static extern int nng_send(nng_socket s, IntPtr buf, int len, int flags);

结构体 双重指针

//c++:结构体 **变量名   ----    c#:out 变量名   //C#中提前申明一个结构体实例化后的变量名

指针变量

int fnAdd(int *p_n1,int *p_n2);
[DllImport("你的dll名称", EntryPoint = "fnAdd", CallingConvention = CallingConvention.Cdecl)]
public static extern int fnAdd(ref int num1,ref int num2);

void*

void* a();
[DllImport("ddd.dll")]
public static System.IntPtr a();

byte[] to IntPtr

IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);

double*

[DllImport(GageBoxMG4C2Lib, SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
static extern int GetAllChannelCurrentValue(double[] AValues, int ALen);

ref

http://ybeernet.blogspot.com/2011/03/techniques-of-calling-unmanaged-code.html

C++/CLI

貌似这个方法不推荐

WARNING
Other methods to create a .NET binding to a C# library exist. A notorious one is based on the compilation of the C++ library with the C++/CLI compiler. To keep things compatible with the Apple macOS, and because the IJW (it just works) technology sometimes does not, we suggest the use of PInvoke.

nuget
github

这个不好用,还是自己使用 invoke 实现了

vs2019 dependencies - righ click menu
NuGet Packages

search ‘MongoDB.Driver’ and install

连接

using MongoDB.Driver;

// mongodb://localhost:27017 mongodb://192.168.0.xx:27017
MongoClient dbClient = new MongoClient("mongodb://localhost");

var dbList = dbClient.ListDatabases().ToList();

var database = dbClient.GetDatabase("stockServiceDoc");
var collection = database.GetCollection<BsonDocument>("capital");

查询

var cursor = collection.Find(highExamScoreFilter).ToCursor();
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document);
}

// all documents
var documents = collection.Find(new BsonDocument()).ToList();

// 正则过滤, 名字 _day 结尾
var dbDatas = client.GetDatabase("stockDataAKShare");
var bre = new BsonRegularExpression("_day$");
var copt = new ListCollectionsOptions
{
Filter =
Builders<BsonDocument>.Filter.Regex("name", bre)
};
var collectionsWithMatchingNames = dbDatas.ListCollections(copt).ToList().Select(col => col["name"]);
foreach (var coll in collectionsWithMatchingNames)
{
// find one document. fetch data
var doc = database.GetCollection<Model_stock_rank>(coll.ToString());
var results = doc.Find(x => x.date == date);
}

排序

var sort = Builders<BsonDocument>.Sort.Descending("student_id");

var highestScores = collection.Find(highExamScoreFilter).Sort(sort);
var highestScore = collection.Find(highExamScoreFilter).Sort(sort).First();

Console.WriteLine(highestScore);

插入

还没找到插入失败的处理方式。遇到问题了在处理吧

public int save_capital(ref Capital obj)
{
var database = dbClient.GetDatabase("stockServiceDoc");
var collection = database.GetCollection<BsonDocument>("capital");
collection.InsertOne(obj.ToBsonDocument());
m_capital.Insert(0,obj);
return 0;
}

更新


<Window x:Class="WpfTutorialSamples.Misc_controls.TabControlSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TabControlSample" Height="200" Width="250">
<Grid>
<TabControl>
<TabItem Header="General">
<Label Content="Content goes here..." />
</TabItem>
<TabItem Header="Security" />
<TabItem Header="Details" />
</TabControl>
</Grid>
</Window>